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