c++ sorting with custom compare function

前端 未结 2 1306
一生所求
一生所求 2021-01-23 13:51

I have a vector of following type:

std::vector< std::pair< std::pair< int, int >, std::vector > >  neighbors;

I

2条回答
  •  渐次进展
    2021-01-23 14:35

    Pre-C++11 solution: use an object instance as a custom comparator

    struct Comparator {
        Comparator(int index) : index_(index) {}
        bool operator () (const std::pair< std::pair< int, int >, std::vector > &a,
                          const std::pair< std::pair< int, int >, std::vector > &b) 
        {
            return ( a.second[index_] > b.second[index_] );
        }
    
        int index_;
    };
    
    sort(neighbors.begin(), neighbors.end(), Comparator(42));
    

    C++11+ solution: use a lambda

    std::sort(neighbors.begin(), neighbors.end(), [index]
                             (const std::pair< std::pair< int, int >, std::vector > &a, 
                              const std::pair< std::pair< int, int >, std::vector > &b) 
      { 
        return ( a.second[index] > b.second[index] );
      }
    );
    

    My advice: go for a lambda if you're allowed to use C++11 features. It's probably more elegant and readable.

提交回复
热议问题