c++ - map 声明未编译

标签 c++ dictionary compiler-errors stl stdmap

<分区>

因此,出于某种原因,这在类构造器中有效,但在类外不起作用,我想知道为什么以及如何让我的 map 在类外工作。

#include <iostream>
#include <string>
#include <map>


typedef std::map <std::string, int> idMap;

idMap type_id;


type_id["Moon"] = 1;
type_id["Star"] = 2;
type_id["Sun"] = 3;


int main()
{

    std::cout << type_id["Moon"] << std::endl;

}

我得到的编译错误如下

11:1: error: 'type_id' does not name a type 12:1: error: 'type_id' does not name a type 13:1: error: 'type_id' does not name a type 

我正在寻找这样一个可行的示例,如果您能告诉我为什么这行不通的话。

最佳答案

您的主要内容应如下所示:

int main()
{
   type_id["Moon"] = 1;
   type_id["Star"] = 2;
   type_id["Sun"] = 3;
   std::cout << type_id["Moon"] << std::endl;
}

您不能将这些语句放在函数之外(在那种情况下 main())。


或者如果你真的想在 main() 之外填充你的 map ,你可以通过使用列表初始化构造函数来实现,如下所示:

idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };

这种方法也适用于头文件,如下所示:

myHeader.h

#include <string>
#include <map>

typedef std::map <std::string, int> idMap;

idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };

主要.cpp

#include <iostream>
#include "myHeader.h"

int main() {
    std::cout << type_id["Moon"] << std::endl;
}

关于c++ - map 声明未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46170771/

相关文章:

c++ - 访问C++空字符串中的任意位置

python - 我可以更改 Python 字典中键的比较方式吗?我想使用运算符 'is' 而不是 ==

scala - 错误: left- and right-associative operators with same precedence may not be mixed

c# - 如何使用 C# 接口(interface)将 C++ 智能指针返回到 PowerPoint 接口(interface)

c++ - 二维数组,调用函数问题

python字典可变澄清

Javascript - 如何从对象构造函数中的字典中检索键

java - 整数不会设置到 JTextField 中

c - 我在这里做错了什么?

c++ - 具有相同名称和签名的多个函数会相互覆盖吗?