c++ - 如何为要在 STL 数据结构中使用的任意结构实现运算符 <?

标签 c++

有时我想在 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/

相关文章:

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - "Logically slower"算法原来更快,但为什么呢?

c++ - std::unordered_set 中的数据是否在函数结束时被删除?

c++ - 清理字符串以打印到终端的惯用方法?

c++ - 我可以从 C 或 C++ 外部控制 Chrome 扩展程序吗?

c++ - 为什么隐式转换不会发生在类型转换的 nullptr 上

c++ - Catch 单元测试订购

c++ - 除了使用 inotify 之外如何递归监视目录

c++ - 使用 while 循环对三角形进行编号

c++ - 使用 C++ 从系统注册表中检索 ActiveX classID