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

标签 c++ set overloading 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_;
};

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

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/

相关文章:

C++ Pseudo-RSA 快速求解大量的 d(解密 key )

c++ - 具有 protected 成员的自定义对象的排序 vector

c++ - C++ 中的 UTF-8 兼容性

c++ - 部分模板特化可能不适用于函数,但重载不是同一件事吗?

Java - 在重载的构造函数调用中创建 HashMap

c++ - 如何在满足条件时在eclipse中停止执行

python - 确保 Set Python 迭代的随机顺序

lua - 如何使用一些命令或 LUA 脚本读取存储在 Redis 上的多个集合

c++ - 无法将元素插入嵌套的 STL 整数集中

c++ - 未调用模板化函数