I wish to sort an array of objects of class Person
on the basis of its data member \'age
\'. I store the objects in a vector
To sort a range using std::sort
(or any function for that matter), it needs to know how two elements from the range are compared, in order to determine less than (or greater than) relationship.
The Standard Library function std::sort
comes in two flavors: one uses operator<
, the other uses a compare function/functor. You've used both of them in your code — in particular, the third one in your example uses <
and the rest use compare function/functor.
As for which one is the best approach?
Well, it depends. The one which uses operator<
is less flexible since it is fixed but requires you less typing as well. Use it when it suffices.
The other one is more flexible as you can pass any compare function and get your elements sorted accordingly. Use it when operator<
doesn't suffice. Also, when you choose this flavor, you have other choices as well : the comparer could be a function, a functor, or a lambda — if you use function or functor (defined at namespace level), then you can reuse them; on the other hand, lambda is usually defined in a function scope, so it is not that reusable, unless you define it at namespace scope, in which case it is almost same as function.
Example, suppose you want to sort a vector of int
in increasing order:
std::vector v{10, 3, 12, -26};
std::sort(v.begin(), v.end());
print(v);
Output: -26,3,10,12
. So operator<
does do the job.
But what if you want the elements sorted considering only magnitude (i.e ignore signs), then you have to use the other flavor:
std::vector v{10, 3, 12, -26};
auto abs_cmp = [](int a, int b) { return std::abs(a) < std::abs(b); };
std::sort(v.begin(), v.end(), abs_cmp);
print(v);
Output : 3,10,12,-26
. That is the output you would expect in this case.
Hope that helps.