为什么我的地图地图全部打印出来?

时间:2014-03-18 02:14:15

标签: c++ map

我正在做以下事情:

//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

1 个答案:

答案 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;
}