DecPK
DecPK

Reputation: 25398

why this program is not printing the correct second element of returned iterator?

I want to change the value of the map element if it is already exist in the map container i.e count the no of the elements in that container

std :: map < int, int > m;
std :: map < int, int > :: iterator itr;

int arr[] = { 10, 40, 20, 20, 20, 20, 20, 20, 10, 30, 10, 30, 40 };

for (int i : arr) {
    itr = m.find(i);
    if (itr == m.end() ) {
        int value = 0;
        m.insert(std :: make_pair(i, value));
    } else {
        ++itr->second;
    }
}
itr = m.begin();
while (itr != m.end() ) {
    std :: cout << itr->first << " -> " << itr->second << std :: endl;
    ++itr;
}

I got wrong output :

10 -> 2
20 -> 5
30 -> 1
40 -> 1

Upvotes: 2

Views: 78

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29023

The problem is with the line int value = 0;. Since the first time you encounter a value, you've encountered it once, not zero times. It should be int value = 1; instead.

Note that for (int i : arr) { m[i] += 1; } would accomplish what your code is trying to do. Contrary to sequential containers, associative containers allow you to access elements that aren't already in the container and value initializes them if they are missing (zero or default initializes them).

Upvotes: 6

Related Questions