Sign in
or
Register
Courses
Textbook
Compiler
Contests
Topics
Computer Science. Textbook
C++. Containers
Sorting with comparator
Sort with comparator
A vector (like an array) can be sorted using the
sort()
function. But this function sorts in ascending order by default. To sort an array in a different order, you need to use the so-called
comparator
- a function that sets the sort order by comparing two objects.
Example
An example of a comparator that sorts the elements of an array in ascending order.
bool cmp(int first, int second) { return first < second; }
and sorting the vector
A
using the created comparator:
sort(A.begin(), A.end(), cmp);
Think about iterators
According to the condition of the problem, it is clear that it is necessary to apply
stable
(stable) sorting, therefore, instead of sort, stable_sort should be used.
you can also specify a function object as a comparator, which you can create before calling the sort function.
For example:
struct
{
bool
operator
()(
int
a,
int
b)
const
{
return
a
<
b; } }cmp;