Open In App

make_reverse_iterator Function in C++

Last Updated : 14 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The std::make_reverse_iterator() is a predefined function in C++ which is used to create the reverse_iterator for the given iterator. This function helps to iterate the data in reverse order.

The std::make_reverse_iterator() function is present in the <iterator> header file.

Syntax

std::make_reverse_iterator (iterator);

Parameters

  • iterator: Iterator to be converted to reverse iterator.

Return Value

  • It returns the reverse iterator of the given type.

Examples of make_reverse_iterator()

Example 1: Traversing vector element in reverse order using make_reverse_iterator.

C++




// C++ Program to illustrate the use of
// make_reverse_iterator for vector iterator
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
  
int main()
{
    // declaring vector
    vector<int> v = { 10, 20, 30, 40, 50 };
  
    // creating a iterator using v.end()
    auto rIter = make_reverse_iterator(v.end());
  
    // printing in reverse order
    for (auto iter = rIter; iter != v.rend(); ++iter) {
        std::cout << *iter << " ";
    }
  
    return 0;
}


Output

50 40 30 20 10 

In this code, we have a vector of size 5 and in the next line, we have created the reverse iterator(rIter) using the make_reverse_iterator() function by passing the end() iterator of the vector. rIter is pointing to the last element of the vector so we just need to iterate the rIter until the rIter point to the first element of the vector.

Example 2: Print the whole string in capital letters in reverse order using the make_reverse_iterator()

C++




// C++ program to print reverse of string in upper case
// using make_reverse_iterator
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
  
int main()
{
    // defining string
    string name = "vikash mishra";
  
    // creating reverse iterator
    auto rIter = make_reverse_iterator(name.end());
  
    // printing string character by character
    for (auto iter = rIter; iter != name.rend(); ++iter) {
        int k = *iter;
        if (k == 32) {
            cout << char(k);
        }
        else {
            cout << char(k - 32) << " ";
        }
    }
    cout << endl;
  
    return 0;
}


Output

A R H S I M  H S A K I V 

In this example we are printing the whole string into capital The approach is similar to the previous example but the major difference is converting the small character into the upper character which is done by subtracting the 32 from the ASCII value of the small character(Ex – ‘a’ ASCII value is 97 so 97-32 = 65 which is the ASCII value of A).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads