Why do we write arr + n in sort function?
Solution 1:
-
std::sort
accepts iterators to beginning and end of some range (end points to first element beyond range). - A pointer can be an iterator
- In
C
an array of typesometype[n]
decays to a pointer of type:sometype*
. Soarr
is treated as a pointer andarr + n
advances this pointer byn
elements (so it point to first element beyond array).
Now alternative ways to write this code to make it more clear and less bug prone:
std::sort(std::begin(arr), std::end(arr));
// or using C++20 ranges:
std::ranges::sort(arr);