我正在尝试将自定义类型指定为 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++ 中使用自定义类型作为映射的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!