我想通过以下方式使用 map
值初始化一个 map
:
std::map<int, std::map<int, int>> map =
{
{ 1, { { 1, 0 }, { 2, 1 } } },
{ 2, { { 1, 1 }, { 2, 0 } } },
};
虽然此编译没有任何错误或警告,但它引发了一个异常,指出“map/set iterators incompatible”。如果我删除第二对,即 { 2, { { 1, 1 }, { 2, 0 } } }
,不会引发异常并且 map
包含一对键 1
和包含对 (1, 0)
和 (2, 1)
作为其值的映射。
我确信这种(乍一看)有些奇怪的行为是有充分理由的。
解决方案
不,没有充分的理由。事实证明这是 Visual Studio 2013 中的一个美丽错误。
最佳答案
您尝试过使用 c++11 选项吗?
#include <iostream>
#include <map>
int main()
{
std::map<int, std::map<int, int>> map =
{
{ 1, { { 1, 0 }, { 2, 1 } } },
{ 2, { { 1, 1 }, { 2, 0 } } },
};
auto t = map[1];
std::cout << t[1] << std::endl;
std::cout << t[2] << std::endl;
auto t2 = map[2];
std::cout << t2[1] << std::endl;
std::cout << t2[2] << std::endl;
std::cout << "--------------" << std::endl;
std::cout << map[1][1] << std::endl;
std::cout << map[1][2] << std::endl;
std::cout << map[2][1] << std::endl;
std::cout << map[2][2] << std::endl;
}
关于c++ - 使用 map 值初始化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24016045/