How can I use a custom type as key for a map in C++?(如何在 C++ 中使用自定义类型作为映射的键?)
问题描述
我正在尝试将自定义类型指定为 std::map 的键.这是我用作键的类型:
I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key:
struct Foo
{
Foo(std::string s) : foo_value(s){}
bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; }
bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; }
std::string foo_value;
};
与 std::map 一起使用时,出现以下错误:
When used with std::map, I am getting the following error:
error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:program filesmicrosoft visual studio 8vcincludefunctional 143
如果我将 struct 更改为下面的那个,一切正常:
If I change the struct to the one below, everything works:
struct Foo
{
Foo(std::string s) : foo_value(s) {}
friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; }
friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; }
std::string foo_value;
};
没有改变,只是操作符被重载为friend.为什么我的第一个代码不起作用?
Nothing changed, except that the operator is overloaded as friend. Why does my first code not work?
推荐答案
我怀疑你需要
bool operator<(const Foo& foo1) const;
注意参数后面的const,这是为了使你的"(比较中的左侧)对象保持不变.
Note the const after the arguments, this is to make "your" (the left-hand side in the comparison) object constant.
只需要一个运算符的原因是它足以实现所需的排序.回答抽象的问题a 必须在 b 之前出现吗?"知道a是否小于b就足够了.
The reason only a single operator is needed is that it is enough to implement the required ordering. To answer the abstract question "does a have to come before b?" it is enough to know whether a is less than b.
这篇关于如何在 C++ 中使用自定义类型作为映射的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中使用自定义类型作为映射的键?
基础教程推荐
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
