Abhishek kumar
Abhishek kumar

Reputation: 45

Why do we write arr + n in sort function?

sort (arr, arr + n)

Why do we write arr + n in sort function in (function in algorithm library) C++. What does it mean arr + n?

Upvotes: 1

Views: 711

Answers (3)

Marek R
Marek R

Reputation: 38092

  1. std::sort accepts iterators to beginning and end of some range (end points to first element beyond range).
  2. A pointer can be an iterator
  3. In C an array of type sometype[n] decays to a pointer of type: sometype*. So arr is treated as a pointer and arr + n advances this pointer by n 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);

Upvotes: 4

asynts
asynts

Reputation: 2423

std::sort takes a pair of iterators and them uses std::swap to sort the elements in that range. The iterators must provide implementations for operator* and operator++. These requirements are defined as "named requirements" here.

If you thing about it, any pointer fulfills these criteria. In other words, you can think of iterators as a generalization of pointers. By passing a pointer to the first &arr[0] and a pointer to one past the last element &arr[n] you are providing the begin and end iterators. arr and arr + n are fancy abbreviations for &arr[0] and &arr[n].

Upvotes: 0

user16004728
user16004728

Reputation:

Given the declaration of type arr[], the expression arr + n is evaluated as the address of the nth element in arr.

In other words (hoping that it helps clarifying), arr + n is equivalent to &arr[n].

Upvotes: 0

Related Questions