This is the mail archive of the
libstdc++@sourceware.cygnus.com
mailing list for the libstdc++ project.
RE: Is this a bug or lack of understanding?
- To: "Chris Picton" <Chris dot Picton at usko dot com>,<libstdc++ at sourceware dot cygnus dot com>
- Subject: RE: Is this a bug or lack of understanding?
- From: "Shiv Shankar Ramakrishnan" <ShivShanks at MailandNews dot com>
- Date: Tue, 18 Apr 2000 19:00:34 +0530
|If I change the commented return line in the sort function object, to
|sort by length of the key, it doesnt print all the entries in the map.
|
|Could someone explain why, or is it a bug?
The first reply you got is correct. But I understand your intent. You
have just programmed it incorrectly. You need to use a multimap for this
to work correctly since map finds that a string with length n already
exists so it doesn't add the new one now. Please change to multimap to
get what you want. (If I read correctly as to what you want.) The
keycomp function s::operator() is used to check for unique keys.
Thanks,
Shiv
See the corrected program below -
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct s {
bool operator()(string s1, string s2) {
return s1.size() < s2.size();
//return s1 < s2;
}
};
int main()
{
multimap<string, int, s> m;
m.insert( make_pair(string("a"),1 ) );
m.insert( make_pair(string("ab"),1) );
m.insert( make_pair(string("ba"),1) );
m.insert( make_pair(string("abc"),1) );
m.insert( make_pair(string("acb"),1) );
m.insert( make_pair(string("bac"),1) );
m.insert( make_pair(string("bca"),1) );
m.insert( make_pair(string("cab"),1) );
m.insert( make_pair(string("cba"),1) );
for (multimap<string, int, s>::iterator i = m.begin(); i != m.end(); i++)
cout << (*i).first << "\t" << (*i).second << endl;
return 0;
}