user1285419
user1285419

Reputation: 2225

It fails to compile a c++ map structure as map<A, pair<B, C> >

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

Answers (2)

eran
eran

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

Jack
Jack

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

Related Questions