访问 c++地图
我正在尝试从 C++ 中的 std:map 中的键访问值
假设 aObject 有效 Mymap 有几个值。
map<myObject,int> mymap;
myObject aObject;
int value = mymap[aObject];
我是否必须为 myObject 重新定义运算符 == ?
如果我不重新定义它会发生什么?
I am trying to access values from keys in a std:map in C++
Assume that aObject is valid
Mymap has several values.
map<myObject,int> mymap;
myObject aObject;
int value = mymap[aObject];
Do I have to redefine operator == for myObject?
What will happen if I don't redefine it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::map
要求您重载键类型的operator<
,或者提供比较器。两者都必须执行严格的弱排序。如果您不提供其中任何一个,您的程序将无法编译。如果你错误地实现它们(即不是严格的弱排序),你会得到垃圾结果(我实际上不知道这实际上是否是严格意义上的未定义行为)。std::map
requires that you either overloadoperator<
for the key-type, or provide a comparator. Both have to implement a strict weak ordering. If you don't provide either, your program will not compile. If you implement them incorrectly (i.e. not as a strict weak ordering) you get garbage results (I actually don't know if this is actually undefined behavior in the strict sense).