2017-08-02 75 views
0

。为什么我的编译器不断抱怨的映射分配我运行在Xcode这个代码警告“C++要求所有申报类型说明符”地图

#include <iostream> 
#include <map> 
#include <deque> 
using namespace std; 

map<int,deque<int>> bucket; 
deque<int> A{3,2,1}; 
deque<int> B; 
deque<int> C; 


bucket[1] = A;//Warning "C++ requires a type specifier for all declaration 
bucket[2] = B;//Warning "C++ requires a type specifier for all declaration 
bucket[3] = C;//Warning "C++ requires a type specifier for all declaration 

int main() { 

    for (auto it:bucket) 
    { 
     cout << it.first << "::"; 
     for (auto di = it.second.begin(); di != it.second.end(); di++) 
     { 
      cout << "=>" << *di; 
     } 
     cout << endl; 
    } 

    return 0; 
} 

在那里,好像我做内部主同样的事情了完美的作品

#include <iostream> 
#include <map> 
#include <deque> 
using namespace std; 

map<int,deque<int>> bucket; 
deque<int> A{3,2,1}; 
deque<int> B; 
deque<int> C; 

int main() { 

    bucket[1] = A; 
    bucket[2] = B; 
    bucket[3] = C; 

    for (auto it:bucket) 
    { 
     cout << it.first << "::"; 
     for (auto di = it.second.begin(); di != it.second.end(); di++) 
     { 
      cout << "=>" << *di; 
     } 
     cout << endl; 
    } 

    return 0; 
} 

输出

1::=>3=>2=>1 
2:: 
3:: 
Program ended with exit code: 0 

有什么事情,我很想念。不能够易懂nd这种行为。 任何建议,帮助或文档。我看着到类似的问题,但没有得到满意的答案

+0

实在是可执行代码没有这样的东西的功能之外的C++。 –

+0

deque A {3,2,1};为什么这个工作? –

+1

因为这是一个变量的声明。这就是“可执行代码”的概念有点模糊的地方。全局变量的构造函数叫做,在这种情况下,它是初始化列表构造函数。 –

回答

5

同时声明在

int i = 100; 

或设置里面的价值你不能做这样的事情在全球范围内

int i; 
i = 100; 

因为在C++ 11你要么初始化值函数

int main() { 
i = 100; 
} 

STL初始化也是如此,这就是为什么你的iss UE

+0

bucket [1] = deque A {3,2,1}; 将上述工作? –

+0

@HariomSingh将'bucket'的定义移动到'deque'后面,然后您可以使用'map user4581301

1

这是因为三线...

bucket[1] = A;//Warning "C++ requires a type specifier for all declaration 
bucket[2] = B;//Warning "C++ requires a type specifier for all declaration 
bucket[3] = C;//Warning "C++ requires a type specifier for all declaration 

的语句。你不能在C中的函数之外执行语句(C不是Python)。如果你在main()中移动这三行代码,那么它应该可以正常工作。

-1

编译器能够识别此代码

bucket[1] = A; 
bucket[2] = B; 
bucket[3] = C; 

declarations其应具有指定的类型,因为你不能运行可执行代码(其调用assignment operator是)外的函数的(或作为与初始化声明变量时)。 在箱子:

map<int,deque<int>> bucket; 
deque<int> A{3,2,1}; 
deque<int> B; 
deque<int> C; 

map<int,deque<int>>deque<int>是类型说明符。

1

你可以做的初始化功能范围之外的变量是

std::deque<int> A{3,2,1}; 
std::deque<int> B; 
std::deque<int> C; 
std::map<int, std::deque<int>> bucket {{1, A}, {2 , B}, {3, C}};