自定义类型作为地图的关键 - C ++ [英] Custom types as key for a map - C++

查看:230
本文介绍了自定义类型作为地图的关键 - 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 配合使用时, 。

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

如果我像下面改变结构,一切都工作。

If I change the struct like the below, everything worked.

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 making the operator overloads as friend. I am wondering why my first code is not working?

任何想法?

推荐答案

我怀疑你需要

bool operator<(const Foo& foo1) const;

请注意 const 在参数之后,这是使your(比较中的左侧)对象常量。

Note the const after the arguments, this is to make "your" (the left-hand side in the comparison) object constant.

原因只需要一个操作符它足以实现所需的顺序。为了回答抽象的问题一定要在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天全站免登陆