如何在C ++中使用自定义类型作为地图的键? [英] How can I use a custom type as key for a map in C++?

查看:258
本文介绍了如何在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 files\microsoft visual studio 8\vc\include\functional 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 ++中使用自定义类型作为地图的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆