How to create a std::set with custom comparator in C++?

孤者浪人 提交于 2019-12-01 10:34:57

问题


How do I create a set of pairs, the elements of which (the pairs) are sorted with a custom bool function? I write

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

and get error : Type/value mismatch at argument 2, expected a type, got "compare"

I have defined "compare" as

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

and of course

#include <vector>
#include <set>

回答1:


Method 1: use functor

Write a class that overloads the operator()so it can be called like a function:

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

Then, you can use the class name as the type parameter

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

Method 2: use function pointer

Assuming compare is the function you want to use:

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



回答2:


You should use a functional object. Here is an example

#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;
}


来源:https://stackoverflow.com/questions/23042947/how-to-create-a-stdset-with-custom-comparator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!