Yize Wang
Yize Wang

Reputation: 11

Wrong indexing with unordered_map

I am having trouble to access the key of unordered_map. Following is my code:

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

int main() {
    vector<int> nums = {1,2,3,4,5};
    int k = 2;
    unordered_map<int,int> mp;
    for(auto num : nums)
        mp[num]++;
    for(auto it : mp)
        cout << it.first;
    cout << endl;
    for(auto it : mp)
        cout << mp[it.first+k];
    return 0;
}

I expected the output to be

54321

00111

because the key value of "7","6","5","4","3" are "0","0","1","1","1". But the output was

54321

0000

Note that there are only four "0" here. I am confused and do not know what the mechanism is. Could anybody help me with this? Thank you in advance.

Upvotes: 1

Views: 119

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

The program has undefined behavior because after this adding the new element mp[it.first+k] for it.first equal to 5 the iterators are invalid.

Upvotes: 2

Related Questions