Why sort(rbegin(), rend()) sort the structure on descending order?

4.9k views Asked by At

for example the code bellow sort the vec on desc order :

std::vector<int> vec = {1, 2, 5, 4, 3};
sort(vec.rbegin(), vec.rend());
for(const auto v : vec)
    std::cout << v << "\n";
output 5 4 3 2 1

On the C++ reference:

Sorts the elements in the range [first,last) into ascending order. The elements are compared using operator< for the first version [...]

1

There are 1 answers

2
Vlad from Moscow On

The function call indeed sorts the vector in the ascending order starting form the last element up to the first element because there are used reverse iterators

sort(vec.rbegin(), vec.rend());

When you are using reverse iterators then the vector is traversed in the reverse order.

Consider this for loop

for (auto first = vec.rbegin(), last = vec.rend(); first != last; ++first)
{
    std::cout << *first << ' ';
}
std::cout << '\n';

Its output is

3 4 5 2 1

If you want to sort the vector in the ascending order in the direct direction then do not use the reverse iterators. For example

sort(vec.begin(), vec.end());

Or if to use the reverse iterators then instead of the default function object of the type std::less<int> you need to use a function object of the type std::greater<int>

sort( vec.rbegin(), vec.rend(), std::greater<int>() );