如何重载并传递 <
(小于)一组整数对的比较器?这是我当前的代码:
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
我该如何解决?
最佳答案
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_;
};
关于c++ - 如何为一组对重载比较运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128665/