c++ - 插入 map 未正确排序

标签 c++ dictionary

我很困惑为什么记录没有在 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;
 }

输出是

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树中插入的工作方式,还是存在其他问题。

最佳答案

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

你需要做的是使用:

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

或者使用已经定义的operator<用于字符串。

return (p1.s1 < p2.s1);

关于c++ - 插入 map 未正确排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262939/

相关文章:

java - 为什么用某些编译器编译的程序可以被反编译而其他的(实际上)不能?

c++ - 传递指针 vector 并删除重复项

Python,在numpy数组中加载.csv,返回一个列表

swift - 使用返回 double 值的用户输入访问字典

python - 如何将 SciPy 稀疏矩阵转换为字典

c# - "unhandy"字典的JSON反序列化

c++ - 如何让Anjuta DevStudio像Eclipse一样提示提示?

c++ - 在 qt (mingw) 中启用 c++1y

c++ - map [] 运算符段错误

C++ - boolean 运算