Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ranges::sort return an iterator?

I can see that std::sort returns void. But now that ranges have been added to the C++20 Standard, why does std::ranges::sort return an iterator? cppreference specifies:

Return value

An iterator equal to last.

  1. What's the rational behind that choice?
  2. What's the use case advantage compared to void?
like image 381
gonidelis Avatar asked Apr 16 '21 15:04

gonidelis


1 Answers

You don't have to pass an end iterator to the algorithms in std::ranges. You can pass a sentinel instead, which is something comparable to an iterator, but it's not itself an iterator (it can't be dereferenced or incremented). Think of how this might be useful if you wanted to pass a null-terminated string to an algorithm.

std::ranges::sort necessarily find the end of the sequence while doing it sorting. That's useful information, so it is returned.

like image 143
Eric Niebler Avatar answered Oct 18 '22 04:10

Eric Niebler