function template
<iterator>

std::prev

template <class BidirectionalIterator>  BidirectionalIterator prev (BidirectionalIterator it,       typename iterator_traits<BidirectionalIterator>::difference_type n = 1);
Get iterator to previous element
Returns an iterator pointing to the element that it would be pointing to if advanced -n positions.

If it is a random-access iterator, the function uses just once operator+ or operator-. Otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) on the copied iterator until n elements have been advanced.

Parameters

it
Iterator to base position.
BidirectionalIterator shall be at least a bidirectional iterator.
n
Number of element positions offset (1 by default).
difference_type is the numerical type that represents distances between iterators of the BidirectionalIterator type.

Return value

An iterator to the element n positions before it.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// prev example
#include <iostream>     // std::cout
#include <iterator>     // std::next
#include <list>         // std::list
#include <algorithm>    // std::for_each

int main () {
  std::list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  std::cout << "The last element is " << *std::prev(mylist.end()) << '\n';

  return 0;
}

Output:

The last element is 90


Complexity

Constant for random-access iterators.
Linear in n for bidirectional iterators.

Iterator validity

No effect.

Data races

The function accesses the iterator, but it is never dereferenced (no pointed object is accessed by the call).

Exception safety

Throws if any of the arithmetical operations performed on the copied iterator throws, providing the same level of guarantee as such operations.

See also