gpt4 book ai didi

c++ - 为什么在使用 operator() 对 std::set 进行排序时必须实现 operator<

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:47 24 4
gpt4 key购买 nike

在代码审查期间,我的一个同事正在使用结构对 std::set 进行排序。我对 C++ 还是很陌生,必须自己实现它才能完全理解它。可悲的是,我遇到了一些困难,因为在我实现了结构的 operator() 之后,MSVC 也强制我实现 operator< 。

如果我使用结构对 std::set 进行排序,有人能解释一下为什么有必要实现这两个运算符吗?我猜不需要 operator< 因为 std::set 调用了一些基本的比较函数?

class Hallo {
int one;
int two;
public:
Hallo(int one, int two);

bool operator < (const Hallo& rhs) const
{
return one < rhs.GetOne();
}

struct cmpStruct{
bool operator()(Hallo const &lhs, Hallo const &rhs) const
{
return lhs.GetOne() < rhs.GetOne();
}

int main(int ac, char* av[]){
const Hallo a{ 1, 1 };
const Hallo b{ 2, 2 };
const Hallo c{ 3, 3 };
const Hallo d{ 5, 5 };

std::set<Hallo, Hallo::cmpStruct> sortedList{};
std::set<Hallo> unsortedList{};

sortedList.insert(b);
sortedList.insert(c);
sortedList.insert(a);
sortedList.insert(d);

unsortedList.insert(b);
unsortedList.insert(c);
unsortedList.insert(a);
unsortedList.insert(d);

最佳答案

Can someone explain me why it is necessary to implement both operator if I use a struct for sorting a std::set?

因为您创建了 std::set 的 2 个实例与 class Hallo作为键,在第一个你明确使用 cmpStruct作为仿函数,但在第二个中你隐式使用 std::lessdocumentation 中所述

template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;

std::less使用“一些基本比较功能”,即 operator< documentation :

Function object for performing comparisons. Unless specialized, invokes operator< on type T.

重点是我的。所以除非你专攻std::less对于 class Hallo或者不会替换 std::lessstd::set用其他东西实例化它需要 operator<作为方法或独立函数。

关于c++ - 为什么在使用 operator() 对 std::set 进行排序时必须实现 operator<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54135401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com