c++ - 使用数组作为映射键不适用于 C++ 11 编译器命令?

标签 c++

我需要使用数组作为映射键,但我收到编译器错误,指示映射声明未命名类型。

我在类似的问题中使用了代码,但即使我选择了 -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/

相关文章:

c++ - 未调用移动构造函数

c++ - 字符串流和二进制数据

c++ - 是否有必要定义来自不同类的 move 构造函数?

c++ - Rapidjson 迭代并获取复杂 JSON 对象成员的值

c++ - QGraphicsRectItem 用鼠标 move 。如何?

c++ - 使用 std::make_shared() 的数据缓存影响

c++ - iostream - 读取带有嵌入空格的字符串

c++ - 将一种类型的 std::vector 转换为另一种类型

c++ - 需要一个 constexpr 来使 for 循环中的值加倍

c++ - 如何覆盖qt中的标签宽度?