gpt4 book ai didi

c++ - c++ 集合中的用户定义数据类型

转载 作者:行者123 更新时间:2023-11-27 22:33:18 25 4
gpt4 key购买 nike

在第一种情况下,代码工作正常,但我在第二种代码中遇到错误,唯一的区别是“<”运算符重载中的“const”,我无法弄清楚原因。两种情况的代码如下1.

class first
{
public:
int y;
bool operator < (first t) const
{
return (y>t.y);
}
};
set<first> f;

2.

class first
{
public:
int y;
bool operator < (first t)
{
return (y>t.y);
}
};
set<first> f;

最佳答案

std::set 的默认比较器是std::less<Key>正如我们在 std::less 上看到的那样它定义:

constexpr bool operator()( const T& lhs, const T& rhs ) const;

它接受 const 参数并返回 lhs < rhs .如果 lhs < rhs 这当然不起作用对 const 参数无效,因为它在你的第二种情况下是因为 bool operator < (first t)无法调用。


编写自己的接受非常量参数的比较器似乎也不起作用,因此看起来这是订购容器的要求,但需要进一步检查标准以确认。

关于c++ - c++ 集合中的用户定义数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252417/

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