Reputation: 2225
I have a code in c++ with stl map with the second parameter defined as a pair
int keys[10] = {1, 1, 1, 2, 3, 4, 5, 7, 6, 6};
char s[5];
map< unsigned int, pair<string, int> > tmpMap;
for (int i=0; i<10; i++)
{
if (tmpMap.find(keys[i])==tmpMap.end())
{
sprintf(s, "%i", keys[i]);
tmpMap.insert(make_pair(keys[i], make_pair(s, 1)));
}
else tmpMap[keys[i]].second++;
}
for (map< unsigned int, pair<string, int> >::iterator it=tmpMap.begin(); it!=tmpMap.end(); ++it)
{
cout << (*it).first << " " << (*it).second << endl;
}
But it fail to compile, it said, no match operator <<. But (*it).first and (*it).second are just string and int, why it doesn't work?
Upvotes: 0
Views: 146
Reputation: 6921
Your (*it).second is pair , you need to have
cout << (*it).first << " " << (*it).second.first << " " <<
(*it).second.first << endl;
This is since when iterating over map, you get pair, then first is the key and second is the value - in your case a pair also.
Upvotes: 1
Reputation: 133557
That's not true, first
is an unsigned int
, while second
is a pair<string,int>
because the iterator of a map doesn't give you directly the pair but the couple key,value.
I guess you should do
pair<string,int> pair = (*it).second;
cout << pair.first << " " << pair.second << endl;
Upvotes: 9