![]() |
VOOZH | about |
std::prev returns an iterator pointing to the element after being advanced by certain number of positions in the reverse direction. It is defined inside the header file iterator. It returns a copy of the argument advanced by the specified amount in the backward direction. 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:
BidirectionalIterator prev (BidirectionalIterator 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 BidirectionalIterator 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 before it.
Output:
v1 = 1 2 3 4 5 6 7 v2 = 8 9 10 1 2 3 4
How can it be helpful ?
v1 = 1 2 3 7 8 9 v2 = 4 5 6 1 2 3
Can we use std::next in place of std::prev ?
One common query that may arise with std::prev is that can std::next be also used with a negative argument to move the iterator in backward direction. Well, the answer is yes.
Output:
v1 = 1 2 3 4 5 6 7 v2 = 8 9 10 1 2 3 4
Explanation: So, we have just used std::next in place of std::prev and changed the second argument from 3 to -3 here and it still serves the same purpose. We can use std::next also, but there are two things that needs to be kept in mind: