【问题标题】:I can't declare a map我不能声明地图
【发布时间】:2013-04-24 00:38:46
【问题描述】:

所以在我的 cpp 文件中,我尝试如下声明一个映射:

map<string, vector<myStruct>> myMap;

在我的文件顶部我写了using namespace std,我也写了#include &lt;string&gt; .

但是我遇到了这些奇怪的错误:

错误:ISO C++ 禁止声明没有类型的“map”

我不知道如何解决它。如果我写 #include &lt;map&gt; 只会导致编译器崩溃。

【问题讨论】:

  • 查看顶部of this document 的“在标题中定义”注释,然后将其包含在内。正如几个答案中提到的,不要using namespace std; 放在你的头文件中。这只是个坏主意。

标签: c++ compiler-construction map iso


【解决方案1】:

你有#include &lt;map&gt;吗?休息看起来有效, 但是,如果您的 C++ 标准不是 C++11,您可能需要添加一个空格:

#include <map>
#include <vector>
#include <string>
using namespace std;

map<string, vector<myStruct> > myMap;
                           ^^^

最好不要使用命名空间std:

#include <map>
#include <vector>
#include <string>

std::map<std::string, std::vector<myStruct> > myMap;

【讨论】:

    【解决方案2】:

    您需要包含map 头文件。

      #include <map>
    

    同时,如果你不使用 C++11,你需要一个空格:

     map<string, vector<myStruct> > myMap;
                               //^^
    

    【讨论】:

      【解决方案3】:

      您还应该包括&lt;map&gt;std::map是通过这个header引入的。

      此外,using namespace std is considered a bad practice。您应该有一个 using 语句或使用带有 std:: 的名称前缀来表示一个完全限定的标识符:

      #include <map>
      #include <string>
      #include <vector>
      
      std::map<std::string, std::vector<myStruct>> myMap;
      

      【讨论】:

        【解决方案4】:

        注意,缺少 using 语句;)

        #include <vector>
        #include <string>
        #include <map>
        
        #include <iostream>
        
        typedef int myStruct;
        
        std::map<std::string, std::vector<myStruct>> myMap;
        
        int
        main()
        {
          std::vector<myStruct> testMe = { 1, 2, 3};
          myMap["myTest"] = testMe;
          std::cout << myMap.size() << std::endl;
          return(0);
        }
        

        【讨论】:

        • @tacp:好点,取决于编译器,>> 可能需要是 >>。这使用 gcc 4.7.2 干净地编译(并运行)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 2011-01-09
        • 2018-04-18
        • 2022-11-17
        • 2021-10-13
        • 2020-08-07
        • 1970-01-01
        相关资源
        最近更新 更多