有时我想在 map 和集合中使用包含多个值的键。我不太关心速度。是否有一种简单或通用的方法来编写 operator < 来比较具有多个值的结构?我自己想出了以下内容,但它很乏味,尤其是当值的数量增加时。谢谢。
struct Properties
{
Properties() {}
Properties
( const string& data1
, const string& data2
, const string& data3
)
: data1(data1)
, data2(data2)
, data3(data3)
{}
string data1;
string data2;
string data3;
bool operator < (const Properties& other) const
{
if (this->data1 == other.data1)
{
if (this->data2 == other.data2)
{
if (this->data3 == other.data3)
{
return false;
}
else
{
return this->data3 < other.data3;
}
}
else
{
return this->data2 < other.data2;
}
}
else
{
return this->data1 < other.data1;
}
}
};
最佳答案
您可以使用 std::tie
为此:
#include <tuple>
bool operator<(Properties S& rhs) const
{
return std::tie(data1, data2, data3) < std::tie(rhs.data1, rhs.data2, rhs.data3);
}
这有效,独立于 dataN
的类型(前提是他们有 operator<
)。
关于c++ - 如何为要在 STL 数据结构中使用的任意结构实现运算符 <?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15385256/