C++ iterator::prev() Function



The C++ iterator::prev() function is just the opposite of the next() function. It returns an iterator pointer that points to the element you get after decrementing the iterator from the current element. It returns a copy of the argument that has been advanced in backward direction by the specified amount.

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::prev() Function −

BidirectionalIterator prev(
   BidirectionalIterator first,
   typename iterator_traits<BidirectionalIterator>::difference_type off = 1);

Parameters

  • first − it indicates the current position.
  • off − 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 prev() function and retrieving the output.

#include <iostream>
#include <iterator>
#include <vector>
int main() {
   std::vector<int> tutorial{ 3, 1, 4 };
   auto it = tutorial.end();
   auto pv = std::prev(it, 3);
   std::cout << *pv << '\n';
}

Output

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

3

Example 2

Look into the another scenario, where we are going to run the loop and apply prev() function to the loop and 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 << "The last element is " << *std::prev(mylist.begin()) << '\n';
   return 0;
}

Output

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

The last element is 10

Example 3

Considering the following example, where we are going to declare array and then applying the prev() function and retrieving the output.

#include<iostream>
#include<iterator>
#include<vector>
using namespace std;
int main() {
   vector<int> mytutorial = {2,4,6,8,10};
   vector<int>::iterator i1 = mytutorial.begin();
   vector<int>::iterator i2 = mytutorial.end();
   auto prevptr = prev(i2, 5);
   cout << "Result: " << *prevptr << " ";
   return 0;
}

Output

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

Result: 2
Advertisements