Reputation: 13
I insert key,value in map,but whatever i change the value in line 14,the value is always equal to zero and line 13 the 'if' statement never been executed. this is the code ,and the compiler is gcc 7.4.0 in ubuntu 18.04
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n;
cin>>n;
int a;
map<int, int> num;
map<int, int>::iterator p;
for (int i = 0;i < n; i++){
cin>>a;
if(num[a]) num[a]++;
else num.insert(make_pair(a,1));
}
for (p=num.begin();p!=num.end(); p++)
cout<<p->first<<" "<<p->second<<endl;
return 0;
}
when I input
6
10 1 10 20 30 20
for the program, I expected output
1 1
10 2
20 2
30 1
but instead it is outputing
1 0
10 0
20 0
30 0
Upvotes: 0
Views: 81
Reputation: 180424
The problem is that
if(num[a])
constructs a key-value pair in num
if a
does not exist. When you try to do
num.insert(make_pair(a,1));
afterwards you can't because now there is already an element with the key of a
in the map. The good news is it is a very simple fix. Changing the loop to
for (int i = 0;i < n; i++){
cin>>a;
num[a]++;
}
will do the right thing because if a
does not exist you'll get a value initialized to zero and then you increment it to one. If you hit a key you've already created, then you'll just increase its value by one.
Upvotes: 5