Is this a bug or lack of understanding?
Shiv Shankar Ramakrishnan
ShivShanks@MailandNews.com
Tue Apr 18 06:26:00 GMT 2000
|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;
}
More information about the Libstdc++
mailing list