代码之家  ›  专栏  ›  技术社区  ›  Agnel Kurian

在C++中实现运算符

  •  13
  • Agnel Kurian  · 技术社区  · 14 年前

    我在一个类中有几个数字字段,例如:

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

    我需要使用这个类的对象作为 std::map . 因此我实施 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;
    }
    

    本文背后的全部原因就是我发现上面的实现过于冗长。应该有更简单的东西。

    5 回复  |  直到 6 年前
        1
  •  4
  •   bshields    14 年前

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

    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;
        }
    }
    
        2
  •  33
  •   M.M    6 年前

    我假设您想要实现词典编纂顺序。

    在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);
    }
    

    因为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);
    }
    
        3
  •  15
  •   Matthieu M.    14 年前

    我想有个误会 map 要求。

    地图 不要求你的班级 operator< 定义。它需要传递一个合适的比较谓词,这很方便地默认为 std::less<Key> 其中使用 运算符; Key .

    你不应该执行 运算符; 把钥匙放在 地图 . 只有为这个类定义它时,才应该实现它:即如果它有意义的话。

    您可以完美地定义谓词:

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

    然后:

    typedef std::map<Key,Value,Compare> my_map_t;
    
        4
  •  0
  •   arch    6 年前

    避免多个缩进的版本是

    bool operator<(const Class1& other) const
    {
        if(a != other.a)
        {
            return a < other.a;
        }
    
        if(b != other.b)
        {
            return b < other.b;
        }
    
        return c < other.c;
    }
    

    作者的“编辑2”版本比此解决方案的比较平均多。(最坏情况6至最坏情况3)

        5
  •  -4
  •   Skizz    14 年前

    你可以这样做:

    return memcmp (this, &other, sizeof *this) < 0;
    

    但这有很多注意事项——比如没有VTBL,我敢肯定还有很多。