【问题标题】:How to create a std::set with custom comparator in C++?如何在 C++ 中使用自定义比较器创建 std::set?
【发布时间】:2014-04-13 12:48:24
【问题描述】:

如何创建一组对,其中的元素(对)使用自定义 bool 函数进行排序?我写

set <pair<int,int>,compare> myset;

并得到错误:参数 2 的类型/值不匹配,需要一个类型,得到“比较”

我将“比较”定义为

bool compare(pair <int,int> g1, pair <int,int> g2)
{
    return (g1.second-g1.first > g2.second-g2.first);
}

当然

#include <vector>
#include <set>

【问题讨论】:

    标签: c++ set comparator std-pair


    【解决方案1】:

    方法一:使用functor

    编写一个重载operator()的类,这样它就可以像函数一样被调用:

    struct compare {
        bool operator() (const pair<int,int> &lhs, const pair<int,int> &rhs) const{
             return (lhs.second-lhs.first > rhs.second-rhs.first);
        }
    };
    

    然后,你可以使用类名作为类型参数

    set<pair<int,int>, compare> myset;
    

    方法二:使用函数指针

    假设compare是你要使用的函数:

    set<pair<int,int>, bool(*)(const pair<int,int> &lhs, 
                               const pair<int,int> &rhs)
       > myset(&compare);
    

    【讨论】:

    • 也可以使用函数。你只需要输入正确的类型。
    【解决方案2】:

    您应该使用功能对象。这是一个例子

    #include <iostream>
    #include <set>
    #include <utility>
    
    struct Compare
    {
        bool operator ()( const std::pair<int, int> &p1, 
                          const std::pair<int, int> &p2 ) const
        {
            return ( p1.second - p1.first  > p2.second - p2.first );
        }
    };
    
    int main() 
    {
        std::set<std::pair<int, int>, Compare> s;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 2021-10-23
      • 1970-01-01
      • 2016-07-07
      • 2010-11-06
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      相关资源
      最近更新 更多