How to reverse a vector in c++

In this tutorial, we will learn how to reverse a vector using c++. Here we will use the STL(standard template library) library. Here STL is a set of c++ template classes. Using the STL library, it is easy to implement this code.

Here we will use template function, that is std:: reverse. Reverse range reverses the order of elements in the range from first to last.

In addition, Reverse function calls iter_swap to swap the elements to the new location. parameters that are passed are the first and the last element of the vector. These parameters contain all the element from first to the last element. This will include the first element but not the last element.
Moreover, reverse() is a predefined function in the header file algorithm. So it seems easy to reverse the elements of a vector by the help of header file algorithm. Here we will easily learn, how to reverse a vector in c++.
Firstly, we will store the numbers in a vector and we will create an iterator for it.

In this tutorial, we will learn techniques to reverse the vector that is more simple and uncomplicated and of course elementary. In conclusion, there are many more functions in the STL that makes the programming simple and unfussy. We can directly use those functions in our code.

Finally, you need to follow all the steps of this code to reverse the elements of the vector.



you may also like :

Pair in STL ( Standard Template Library ) in C++
push_back() and pop_back() function in C++ STL

REVERSE A VECTOR in C++

#include<iostream>
#include<bits/stdc++.h>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    //Get the vector
    vector <int> v={1 ,54, 23 , 45 , 2, 87 , 56 ,9, 4 };
   
    //create an iterator
    vector <int> :: iterator itr;

    //print the vector     
    cout<<"before reversing  ";
    cout<<endl;
    for(int i=0 ;i<v.size();i++)
    {
        
       cout<<v[i]<<" ";
         
    }

 
    // reverse the vector here
    reverse(v.begin(),v.end());
    //print the reverse vector
    cout<<endl<<" after reversing";
    cout<<endl;

    for(int i=0 ;i<v.size();i++)
       {
         cout<<v[i]<<" ";
       }
   
   return 0;
}

 

 

OUTPUT  EXAMPLE:

Before reversing
1 54 23 45 2 87 56 9 4
After reversing
4 9 56 87 2 45 23 54 1

Leave a Reply

Your email address will not be published. Required fields are marked *