c++ sorting with custom compare function

前端 未结 2 1284
一生所求
一生所求 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<float> > &a,
                          const std::pair< std::pair< int, int >, std::vector<float> > &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<float> > &a, 
                              const std::pair< std::pair< int, int >, std::vector<float> > &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.

    0 讨论(0)
  • 2021-01-23 14:37

    Lambdas:

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

    See What is a lambda expression in C++11? for a detailled introduction.

    0 讨论(0)
提交回复
热议问题