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

前端 未结 2 1500
野的像风
野的像风 2021-01-15 20:15

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

set ,compare> my         


        
相关标签:
2条回答
  • 2021-01-15 20:59

    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;
    }
    
    0 讨论(0)
  • 2021-01-15 21:11

    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);
    
    0 讨论(0)
提交回复
热议问题