I have a vector of following type:
std::vector< std::pair< std::pair< int, int >, std::vector > > neighbors;
I
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.
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.