插入地图未正确排序

时间:2016-02-08 05:34:47

标签: c++ dictionary

我很困惑为什么记录没有在地图中排序。

 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;
 }

输出

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

但预期的输出是

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

有人可以澄清一下,这是插入在RB树中工作的方式,还是存在其他一些问题。

2 个答案:

答案 0 :(得分:3)

如果LHS应该小于RHS,则operator<函数需要返回truestd::string::compare()不会返回这样的值。它返回负值,零或正值。

您需要做的是:

return (p1.s1.compare(p2.s1) < 0 );

或使用已定义的operator<表示字符串。

return (p1.s1 < p2.s1);

答案 1 :(得分:0)

我认为string :: compare()返回一个int值。充其量这将被隐式转换为bool。你可能会因为没有正确处理这个问题而弄乱你的操作员