make_reverse_iterator Function in C++
Last Updated :
14 Jul, 2023
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++
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 10, 20, 30, 40, 50 };
auto rIter = make_reverse_iterator(v.end());
for ( auto iter = rIter; iter != v.rend(); ++iter) {
std::cout << *iter << " " ;
}
return 0;
}
|
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++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main()
{
string name = "vikash mishra" ;
auto rIter = make_reverse_iterator(name.end());
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).
Share your thoughts in the comments
Please Login to comment...