Why use std :: next instead of adding an integer to the pointer?

I just have a quick question. I can't understand the benefits of using std::next for simply adding the desired number of promotions to the pointer. A simple example:

  int main() { int arr [] = {1, 2, 3, 4, 5}; cout << *(arr + 2) << ", "; //example 1 cout << *std::next(arr, 2) << endl; //example 2 return 0; } 

Output: 3, 3

Logically, Example 1 should be faster, since no function is called, etc. In addition, in the instance in which I ran this code, if I added a number that would cause the pointer to be out of bounds (for example, 7), the compiler will give an error in example 1, but will gladly continue and give me the memory address in example 2. This contradicts what I thought at first: that std::next will give some sort of warning or something if the pointer was out of bounds.

Any enlightenment will be appreciated.

+5
source share
2 answers

Because std::next intended not only for working with source pointers, but also for all iterators, therefore it is more universal.

Your assumption is also incorrect. Both approaches are likely to lead to the same build using a reasonable level of optimization. Again, C ++ is intended to simplify this optimization. In your example, the main type of the iterator is an explicit pointer, and it is pretty trivial to infer that a function call can be inlined.

EDIT:

As Matt said in his comment, iterators are more than just a fancy name and shell pattern. There are data structures (containers) that are not in a contiguous segment of memory (for example, a map or set ), they need to use more logic to determine the exact location in memory. Iterators also wrap this, they provide a level of abstraction between the algorithms and the container.

Thus, summing above points, using standard idioms helps in writing more reliable code, i.e. support for various types of containers (not caring about their memory layout), while maintaining efficiency, when possible, due to fairly smart compilers.

+9
source

std::next works with all types of iterators. If you know that you are dealing with an array, adding a value works fine. However, if you write a generic function that you want to work with different iterators, this creates a problem.

 iter + 5 

This operation is defined only for random access iterators.

 std::next(iter, 5) 

However, this operation is defined for advanced iterators, which is a much wider category of iterator. In short, std::next makes your code more general.

cplusplus.com has a complete list of operators supported by the various types of iterators available here . As the diagram on this page shows, all random access iterators are also the first, but not nearly all forward iterators are random access. Things like linked lists will only work with std::next

+7
source

All Articles