如何为一组对重载比较运算符?

问题描述 投票:2回答:4

如何重载并将<(小于)比较器传递给一组整数?这是我目前的代码:

class A{
public:
    typedef std::pair<int, int> pair_type;  

    bool operator<(const pair_type& a, const pair_type& b){ 
        if (a.first < b.first) return true;
        else if ( (a.first == b.first) && (a.second < b.second) ) return true;
        else return false;
    }

private:
    std::set< pair_type > edge_;
};

如果我尝试编译此代码,那么我会收到以下错误:

error: 'bool A::operator<(const pair_type&, const pair_type&)' must take exactly one argument

我该如何解决?

c++ set overloading comparator std-pair
4个回答
5
投票
class A{
public:
    typedef std::pair<int, int> pair_type;  

    struct compare {
        bool operator()(const pair_type& a, const pair_type& b) {
          if (a.first < b.first) return true;
          else if ( (a.first == b.first) && (a.second < b.second) ) return true;
          else return false;
        }   
    };

  private:
    std::set<pair_type, compare> edge_;
};

4
投票

您应该将操作符重载定义为类成员(具有单个参数,通常是同一类的另一个实例):

class pair_type : public std::pair<int, int>
{
public:
    bool operator<(const pair_type &comp) const
    {
        if (this->first < comp.first) return true;
        else if ( (this->first == comp.first) && (this->second < comp.second) ) return true;
        else return false;
    }
};

2
投票

你的运算符应该是自由函数(不是成员函数),因为它与A类没有任何关系。


1
投票

C++11开始,你也可以使用lambda expression而不是定义比较器结构:

using pair_type = std::pair<int, int>;

auto comp = [](const pair_type& a, const pair_type& b) {
    return (a.first < b.first) || ((a.first == b.first) && (a.second < b.second));
};

我还压缩了比较器代码以节省两行。现在,您可以按以下方式定义集合:

std::set<pair_type, decltype(comp)> edge_(comp);

但是,如果你想将上面的比较器用于一个类成员的集合,那么它就不那么舒服了,因为你必须将比较器传递给constructor of the set,如上所示。这意味着,您必须在构造函数定义的初始化列表中移交比较器:

class A{
public:
    A() : edge_(comp) {}

private:
    std::set<pair_type, decltype(comp)> edge_;
};

Code on Ideone

© www.soinside.com 2019 - 2024. All rights reserved.