简体   繁体   English

迭代c ++ map时出现奇怪的行为

[英]strange behaviour while iterating through c++ map

I have the following program which finds the frequency of the numbers. 我有以下程序,可以找到数字的频率。

map<int,int> mp;
vector<int> x(4);
x[0] = x[2] = x[3] = 6;
x[1] = 8;

for(int i=0;i<x.size();++i)
    mp[x[i]]++;

cout<<"size:"<<mp.size()<<endl; //Prints 2 as expected

for(int i=0;i<mp.size();++i) //iterates from 0->8 inclusive
    cout<<i<<":"<<mp[i]<<endl;

The output is as follows: 输出如下:

size:2
0:0
1:0
2:0
3:0
4:0
5:0
6:3
7:0
8:1

Why does it iterate over 9 times? 为什么迭代次数超过9次? I also tried using insert instead of [] operator while inserting elements, but the result is the same. 在插入元素时我也尝试使用insert而不是[]运算符,但结果是一样的。 I also tested by iterating over the map using iterator. 我还使用迭代器迭代地图进行测试。

Before your printing loop, the populated mp elements are [6] and [8] . 在打印循环之前,填充的mp元素是[6][8] When you call cout ... << mp[i] to print with i 0 , it inserts a new element [0] with the default value 0 , returning a reference to that element which then gets printed, then your loop test i < mp.size() actually compares against the new size of 3 . 当你调用cout ... << mp[i]i 0打印时,它会插入一个新元素[0] ,默认值为0 ,返回对该元素的引用然后被打印,然后你的循环测试i < mp.size()实际上与新的3大小进行比较。 Other iterations add further elements. 其他迭代添加了更多元素。

You should actually do: 你应该这样做:

for (std::map<int,int>::const_iterator i = std::begin(mp);
     i != std::end(mp); ++i)
    std::cout << i->first << ':' << i->second << '\n';

...or, for C++11... ...或者,对于C ++ 11 ......

for (auto& e : mp)
    std::cout << e.first << ':' << e.second << '\n';

When you access mp[i] , the element is added to the map if it doesn't already exist. 当您访问mp[i] ,如果该元素尚不存在,则该元素将添加到地图中。 So the first iteration of the loop will attemp to read mp[0] . 所以循环的第一次迭代将尝试读取mp[0] This will create the element, so now mp.size() == 3 . 这将创建元素,所以现在mp.size() == 3 The size will continue to increase whenever an iteration attempts to access an element that doesn't exist. 只要迭代尝试访问不存在的元素,大小就会继续增加。

When you get to i == 8 , the element exists, so it doesn't increase the size. 当你到达i == 8 ,元素存在,所以它不会增加大小。 When it gets back to the top of the loop and tests 9 < mp.size() , it will fail and the loop ends. 当它返回到循环的顶部并测试9 < mp.size() ,它将失败并且循环结束。

Because when you use mp[i] in the printing loop you create those items that doesn't exist in the map. 因为当您在打印循环中使用mp[i] ,您将创建地图中不存在的项目。

Use iterators instead, 改为使用迭代器,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM