std::next in C++
Last Updated :
02 Aug, 2017
std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file .
It does not modify its arguments and returns a copy of the argument advanced by the specified amount. If it is a random-access iterator, the function uses just once operator + or operator – for advancing. Otherwise, the function uses repeatedly the increase or decrease operator (operator ++ or operator –) on the copied iterator until n elements have been advanced.
Syntax:
ForwardIterator next (ForwardIterator it,
typename iterator_traits::difference_type n = 1);
it: Iterator to the base position.
difference_type: It is the numerical type that represents
distances between iterators of the ForwardIterator type.
n: Total no. of positions by which the
iterator has to be advanced. In the syntax, n is assigned
a default value 1 so it will atleast advance by 1 position.
Returns: It returns an iterator to the element
n positions away from it.
#include <iostream>
#include <iterator>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
deque< int > v1 = { 1, 2, 3, 4, 5, 6, 7 };
deque< int > v2 = { 8, 9, 10 };
deque< int >::iterator i1;
i1 = v1.begin();
deque< int >::iterator i2;
i2 = std::next(i1, 4);
std::copy(i1, i2, std::back_inserter(v2));
cout << "v1 = " ;
int i;
for (i = 0; i < 7; ++i) {
cout << v1[i] << " " ;
}
cout << "\nv2 = " ;
for (i = 0; i < 7; ++i) {
cout << v2[i] << " " ;
}
return 0;
}
|
Output:
v1 = 1 2 3 4 5 6 7
v2 = 8 9 10 1 2 3 4
How can it be helpful ?
- Advancing iterator in Lists: Since, lists support bidirectional iterators, which can be incremented only by using ++ and – – operator. So, if we want to advance the iterator by more than one position, then using std::next can be extremely useful.
#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list< int > v1 = { 1, 2, 3, 7, 8, 9 };
list< int > v2 = { 4, 5, 6 };
list< int >::iterator i1;
i1 = v1.begin();
list< int >::iterator i2;
i2 = std::next(i1, 3);
std::copy(i1, i2, std::back_inserter(v2));
cout << "v1 = " ;
int i;
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
cout << *i1 << " " ;
}
cout << "\nv2 = " ;
for (i1 = v2.begin(); i1 != v2.end(); ++i1) {
cout << *i1 << " " ;
}
return 0;
}
|
Output:
v1 = 1 2 3 7 8 9
v2 = 4 5 6 1 2 3
Explanation: Here, just look how if we want copy only a selected portion of the list, then we can make use of std::next, as otherwise we cannot use any +=, -= operators with bidirectional iterators supported by lists. So, we used std::next and directly advanced the iterator by three positions.
Share your thoughts in the comments
Please Login to comment...