Programmers learn & share
11 views

For reversing a string in c++ we can use the inbuilt function, printing reverse string and by creating our own function. In this article, we are going to learn how to reverse a vector?

Example

I am assuming that you already know about the vectors. Here we are taking an example of vector and we are going to reverse it.

 

Vec = {1, 2, 3, 4, 5, 6}

The output of this vector after reversing it will be like this.

{6, 5, 4, 3, 2, 1}

Method

For reversing the vector we can use the reverse function provided in STL.

 

Syntax

reverse(start_index, last_index);

 

Program

#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    vector<int> a = {1, 2, 3, 4, 5, 6}; 
   
    cout << "Vector: "; 
    for (int i = 0; i < a.size(); i++) 
        cout << a[i] << " "; 
    cout << endl; 
  
     reverse(a.begin(), a.end()); 
  
    
    cout << "Reversed Vector: "; 
    for (int i = 0; i < a.size(); i++) 
        cout << a[i] << " "; 
    cout << endl; 
  
    return 0; 
} 

If you have any doubts you can ask freely in the comment section.

posted May 22 in c++ by (100 points)   | 11 views
2,221 questions
2,698 answers
59 comments
241 users