c++ - Insertion into map not sorted properly -
i confused why records not sorted in map.
class point{ public: string s1,s2; public: point(string string1, string string2){ s1=string1;s2=string2; } }; bool operator<(const point &p1, const point &p2) { cout<<"p1.s1.compare(p2.s1)="<<p1.s1.compare(p2.s1)<<" p1.s1="<<p1.s1<<" p2.s1="<<p2.s1<<endl; return p1.s1.compare(p2.s1); } int main(int argc, char *argv[]) { std::map<point,int>m1; point p1("hello","hi"); m1.insert(std::make_pair(p1,1)); point p2("abc","kbd"); m1.insert(std::make_pair(p2,2)); point p3("hell","hi"); m1.insert(std::make_pair(p3,3)); std::map<point,int>::iterator it=m1.begin(); while(it!=m1.end()) { cout<<"m1.first="<<it->first.s1<<" m1.first.s2="<<it->first.s2<<" m1.second="<<it->second<<endl; it++; } return 0; }
the output is
m1.first=hell m1.first.s2=hi m1.second=3 m1.first=abc m1.first.s2=kbd m1.second=2 m1.first=hello m1.first.s2=hi m1.second=1
but output expected was
m1.first=abc m1.first.s2=kbd m1.second=2 m1.first=hell m1.first.s2=hi m1.second=3 m1.first=hello m1.first.s2=hi m1.second=1
could please clarify, way insertion works in rb tree, or other problem exists.
the operator<
function needs return true
if lhs supposed less rhs. std::string::compare()
not return such value. returns negative value, zero, or positive value.
what need use:
return (p1.s1.compare(p2.s1) < 0 );
or use defined operator<
strings.
return (p1.s1 < p2.s1);
Comments
Post a Comment