【发布时间】:2019-01-10 19:07:39
【问题描述】:
在代码审查期间,我的一位同事正在使用结构对 std::set 进行排序。我对 C++ 还是很陌生,必须自己实现它才能完全理解它。可悲的是,我遇到了一些困难,因为在我实现了结构的 operator() 之后,MSVC 也强迫我实现了 operator
如果我使用结构对 std::set 进行排序,有人可以解释一下为什么必须同时实现这两个运算符吗?我猜想不需要 operator
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);
【问题讨论】:
-
其实,你有一些选择:1) 为你的
stuct重载operator<; 2) 编写一个独立的函数用于比较structs 并将其传递给std::sort或std::set; 3) 编写一个函数对象,重载operator<用于比较structs。 -
为什么
std::set<Hallo> unsortedList{};叫unsortedList? 所有集都已排序。 -
不确定这里问的是什么。如果没有为
set提供比较器(如在第二个示例中),则调用默认std::less,这反过来将调用结构本身上的运算符小于(独立或成员)。这就是为什么在第二种情况下您必须自己提供这样的运算符。 -
@ThomasMatthews 你错过了一个 -
std::less的专业化