<在map中使用struct作为键时未调用操作符
overloading of < operator not called when using struct as key in map?
我明白了,我们必须为<操作符>操作符>
希望我的理解是正确的。
考虑下面的代码片段
struct Node
{
int a;
};
// This is not called
bool operator< (const Node &p_node1,const Node &p_node2)
{
printf("nCALLED OPERATOR OVERLOADING");
return true;
}
int main()
{
using namespace std;
map<Node,int> my_map;
Node n1;
n1.a=55;
my_map[n1]=2; // operator overloading should be called
return 0;
}
问题是操作符重载函数没有调用?
编辑:从下面的答案中,在向容器中再添加一对操作符后,调用重载操作符。但是为什么它被称为三次,这里比较了什么?
当映射为空时,不需要调用比较器,因为没有东西可以比较。
在空映射中插入唯一的元素,因此永远不会调用比较操作符。尝试在my_map
中拥有多个元素。
map中至少有2个元素用于调用比较操作符
Node n1;
n1.a=55;
my_map[n1]=2; // operator overloading should be called
Node n2;
n2.a=55;
my_map[n2]=3;
见下面修改后的示例代码。
http://ideone.com/iGY9Xa相关文章:
- 返回类型为struct的函数每次调用时都不返回任何内容
- 调用struct类构造函数
- 指向struct的指针,包含指向对象的指针,我想调用一个函数
- boost::make_shared没有调用(放置)操作符new
- 通过调用Move赋值操作符实现Move构造函数
- 如何从复制赋值操作符调用复制构造函数
- 我如何使用“函数调用操作符”来加载“右值”类型到我的对象
- 多个操作符重载会导致歧义调用
- 不同的强制转换操作符被不同的编译器调用
- 使用c#调用返回struct数组的非托管dll函数
- 有没有一种方法可以通过函数指针来调用操作符函数?
- 使用:TYPENAME没有提供调用操作符,从pair获取值失败
- 是否不可能手动调用c++操作符?
- 重载函数调用操作符和赋值
- 从另一个操作符重载函数调用操作符重载函数:性能
- 编译器如何处理函数函数中重载的函数调用操作符
- 如何通过模板调用操作符重载
- 为什么构造函数不调用函数调用操作符
- <在map中使用struct作为键时未调用操作符
- Const调用操作符调用绑定的非Const成员函数