如何在 C++ 中使用自定义类型作为映射的键?

2023-07-01C/C++开发问题
0

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6