为什么地图需要实现'operator<'以及如何比较对象?

Why maps need to implement the 'operator<' and how are the objects then compared?

本文关键字:何比较 对象 比较 lt 地图 实现 operator 为什么      更新时间:2023-10-16

所以如果你想使用自定义对象作为键,地图需要你实现operator <

struct example{
example( int id, String stuff);
int id;
String stuff;
bool operator<( const example& rhs ) const;
}
bool example::operator<( const example& rhs ) const
{
if( id< rhs.id ) return true;
if( rhs.id< id) return false;
if( stuff< rhs.stuff) return true;
if( rhs.stuff< stuff) return false;
return false;
}

从我看到的例子中(请参阅讨论:为什么 std::map 重载运算符<不使用比较)如果lhs < rhs返回true...>

  1. 为什么 map 需要您实现<运算符?是因为地图在后台进行二分搜索以查找键是否匹配吗?
  2. 即使它正在进行二分搜索,它仍然必须比较对象是否在最后相等,对吗?
example example1 = example(1,"a");
example example2 = example(2,"b");
map<example, String> mymap; 
mymap.insert({example1,"hello"});
mymap.insert({example2,"world"});
cout << mymap[example(1,"a")] << endl;

它从不要求实现operator=所以它怎么知道我创建的新对象与地图的第一个条目相同。它会打印"你好"吗?

它将值存储在平衡的二叉树中,像往常一样红黑树,因此此树需要比较运算符

还要记住,如果a < b == falseb < a == false则认为a等于b