C++ iterator::next() Function



The C++ iterator::next() function returns an iterator that points to the element you got after incrementing the iterator pointer from the current element. It returns a copy of the argument that has been advanced by the specified amount without changing the original argument.

The function only employs operator+ or operator- once if it is a random-access iterator. Otherwise, until n elements have been advanced, the function repeatedly applies the increase or decrease operator (operator++ or operator) to the copied iterator.

Syntax

Following is the syntax for C++ iterator::next() Function −

ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1);

Parameters

  • it − it indicates the current position.
  • n − it indicates the number of times it have to be iterate.

Example 1

Let's consider the following example, where we are going to use the next() function and retrieving the output.

#include <iostream>
#include <iterator>
#include <vector>
int main() {
   std::vector<int> tutorial{ 11,22,33,44 };
   auto it = tutorial.begin();
   auto nx = std::next(it,1);
   std::cout << *it << ' ' << *nx << '\n';
}

Output

When we compile and run the above program, this will produce the following result −

11 22

Example 2

In the following example, we are going to declare to array and apply next() function to the second array and which returns the complete second array along with four elements of first array.

#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
using namespace std;
int main() {
   list<int> t1 = {123,234,345,456,567,678};
   list<int> t2 = { 11,22,33,44};
   list<int>::iterator i1;
   i1 = t1.begin();
   list<int>::iterator i2;
   i2 = std::next(i1, 4);
   std::copy(i1, i2, std::back_inserter(t2));
   cout << "\nResult = ";
   for (i1 = t2.begin(); i1 != t2.end(); ++i1) {
      cout << *i1 << " ";
   }
   return 0;
}

Output

On running the above program, it will produce the following result −

Result = 11 22 33 44 123 234 345 456 

Example 3

Considering the following example, where we are going to run the loop and applying the next() function to retrieving the output.

#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
int main () {
   std::list<int> mylist;
   for (int i = 0; i < 10; i++) mylist.push_back (i*1);
   std::cout << "mylist:";
   std::for_each (mylist.begin(),
      std::next(mylist.begin(),4),
   [](int x) {
      std::cout << ' ' << x;
   } );
   std::cout << '\n';
   return 0;
}

Output

On running the above program, it will produce the following result −

mylist: 0 1 2 3
Advertisements