If I have a vector of pairs:
std::vector<std::pair<int, int> > vec;
Is there and easy way to sort the list in increasing order based on the second element of the pair?
I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less
to do the work directly?
EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
Best Answer
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type
auto
. This is my current favorite solutionORIGINAL ANSWER:
Just use a custom comparator (it's an optional 3rd argument to
std::sort
)If you're using a C++11 compiler, you can write the same using lambdas:
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
then you can do this too:
or even
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P