我需要使用数组作为映射键,但我收到编译器错误,指示映射声明未命名类型。
我在类似的问题中使用了代码,但即使我选择了 -std=c++0x 或 -std=c++11 编译器命令,代码也无法编译。
我使用的代码是:
typedef std::array<unsigned int, 3> alphabet;
std::map<alphabet, std::string> dictionary;
dictionary[{{1, 0, 8}}] = "hello";
错误是:
error: 'dictionary' does not name a type| error: expected unqualified-id before ']' token| ||=== Build finished: 2 errors, 0 warnings (0 minutes, 1 seconds) ===|
即使在谷歌搜索时,我也很少看到这个主题。我使用 CodeBlocks 作为我的 IDE,并选择了上面提到的编译器命令。
最佳答案
我认为错误可能是因为您试图在文件范围内分配给 dictionary
。正如所指出的,变量应该在全局范围内初始化,即:
std::map<alphabet, std::string> dictionary = { {{1,0,8}, "hello"} };
否则,你应该把它放在 block 范围内,即在 main()
中。
#include <array>
#include <map>
typedef std::array<unsigned int, 3> alphabet;
std::map<alphabet, std::string> dictionary;
int main()
{
dictionary[{{1, 0, 8}}] = "hello";
}
作为旁注,大括号似乎可以省略。您不需要两副牙套。 dictionary[{1, 0, 8}]
就足够了。
关于c++ - 使用数组作为映射键不适用于 C++ 11 编译器命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297748/