Isabela
Isabela

Reputation: 156

c++ sorting with custom compare function

I have a vector of following type:

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

I would like to create sort the following vector as follows

std::sort( neighbors.begin(), neighbors.end(), myFunc(index) );

where,

bool myFunc( const std::pair< std::pair< int, int >, float > &a, const std::pair< std::pair< int, int >, float > &b, const int index ){
     return ( a.second[index] > b.second[index] );
}

I know that the syntax is wrong but I wish to provide an index for comparing only that element of the vector.

I am not sure how to pass this argument to myFunc.

Upvotes: 1

Views: 7459

Answers (2)

deviantfan
deviantfan

Reputation: 11414

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.

Upvotes: 1

Marco A.
Marco A.

Reputation: 43662

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.

Upvotes: 1

Related Questions