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>());
Try swapping the elements of the pairs so you can use
std::sort()
as normal.Its pretty simple you use the sort function from algorithm and add your own compare function
Now you have to make the comparison based on the second selection so declare you "myComparison" as
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 solutionJust 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
With C++0x we can use lambda functions:
In this example the return type
bool
is implicitly deduced.Lambda return types
When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type. From C++11, §5.1.2/4:
To explicitly specify the return type use the form
[]() -> Type { }
, like in:You'd have to rely on a non standard select2nd
You can use boost like this:
I don't know a standard way to do this equally short and concise, but you can grab
boost::bind
it's all consisting of headers.