I have a vector of tuples like
vector> v;
I believe that when the default comparison kicks in for tuple types, i
Yes, you can define custom sorting in C++ when you need it. I assume you need it for std::sort
, right? Look at the documentation of std::sort, at the second version of the algorithm to be precise, the one which takes the comp
argument.
You have to define a less-than functor, something like this:
struct CustomLessThan
{
bool operator()(tuple const &lhs, tuple const &rhs) const
{
return std::get<1>(lhs) < std::get<1>(rhs);
}
};
And then use it in std::sort
:
std::sort(v.begin(), v.end(), CustomLessThan());
In C++11, you can make the code much shorter by using a lambda instead of creating a named struct. The examples given at cppreference.com also show this technique.