我正在做以下事情:
//d = 3701
//h = 3702
//c = 8
map<int, map<int,int> > table;
table[d][h] = c;
table iter = table.begin();
while(iter != table.end())
{
cout << "d: " << iter->first << "h: " << iter->second[0] << "c: " << iter->second[1] << endl;
iter++;
}
但我的输出显示:d: 3701 h: 0 c: 0
答案 0 :(得分:2)
此地图上唯一的元素是key = 3701
,这是一张只有1
元素,其中键3702
等于8
的地图。如果您尝试访问任何其他元素,如
iter->second[0] // inner map has no key = 0, so key = 0 with default value
// assigned to it is created
iter->second[1] // inner map has no key = 1, so key = 1 with default value
// assigned to it is created
std::map
会为其插入默认值。
如果你想在检查它们是否存在时避免插入默认值,你应该使用find()
函数与map.end()
迭代器进行比较。
while( iter != table.end())
{
cout << "d: " << iter->first;
if ( (iter->second).find(0) != (iter->second).end())
cout << "key 0, value: " << iter->second[0] << endl;
++iter;
}