在C++中实现operator <

Agn*_*ian 14 c++ operator-overloading operators operator-keyword

我有一个包含几个数字字段的类,例如:

class Class1 {
    int a;
    int b;
    int c;
public:
    // constructor and so on...
    bool operator<(const Class1& other) const;
};
Run Code Online (Sandbox Code Playgroud)

我需要使用这个类的对象作为一个键std::map.因此,我实施operator<.operator<在这里使用最简单的实现是什么?

编辑:<只要任何字段不相等 ,就可以假设其含义以保证唯一性.

编辑2:

一个简单的实现:

bool Class1::operator<(const Class1& other) const {
    if(a < other.a) return true;
    if(a > other.a) return false;

    if(b < other.b) return true;
    if(b > other.b) return false;

    if(c < other.c) return true;
    if(c > other.c) return false;

    return false;
}
Run Code Online (Sandbox Code Playgroud)

这篇文章背后的全部原因只是我发现上面的实现过于冗长.应该有更简单的东西.

ava*_*kar 35

我假设你想要实现词典排序.

在C++ 11之前:

#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
bool Class1::operator<(const Class1& other) const
{
    return boost::tie(a, b, c) < boost::tie(other.a, other.b, other.c);
}
Run Code Online (Sandbox Code Playgroud)

从C++ 11开始:

#include <tuple>
bool Class1::operator<(const Class1& other) const
{
    return std::tie(a, b, c) < std::tie(other.a, other.b, other.c);
}
Run Code Online (Sandbox Code Playgroud)

  • 使用最近的编译器,你可以在包含<tuple>头文件后使用std :: tie :) (5认同)

Mat*_* M. 15

我认为对map需要的内容存在误解.

map不要求你的班级operator<定义.它需要一个合适的比较谓词被传递,这方便地默认为std::less<Key>它使用operator<Key.

你不应该实现operator<适合你的密钥map.只有在为此类定义它时才应实现它:即它是否有意义.

你可以完美地定义一个谓词:

struct Compare: std::binary_function<Key,Key,bool>
{
  bool operator()(const Key& lhs, const Key& rhs) const { ... }
};
Run Code Online (Sandbox Code Playgroud)

然后:

typedef std::map<Key,Value,Compare> my_map_t;
Run Code Online (Sandbox Code Playgroud)


bsh*_*lds 5

这取决于订购是否对您很重要。如果没有,您可以这样做:

bool operator<(const Class1& other) const
{
    if(a == other.a)
    {
         if(b == other.b)
         {
             return c < other.c;
         }
         else
         {
             return b < other.b;
         }
    }
    else
    {
        return a < other.a;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这比OP提供的“简单实现”更好。此版本可读性较差。 (10认同)