Pip*_*ppi 2 c++ overloading set comparator std-pair
如何重载并将<(小于)比较器传递给一组整数对?这是我目前的代码:
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_;
};
Run Code Online (Sandbox Code Playgroud)
如果我尝试编译此代码,那么我会收到以下错误:
error: 'bool A::operator<(const pair_type&, const pair_type&)' must take exactly one argument
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
您应该将运算符重载定义为类成员(使用单个参数,通常是同一类的另一个实例):
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;
}
};
Run Code Online (Sandbox Code Playgroud)
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_;
};
Run Code Online (Sandbox Code Playgroud)