How to reverse a Vector using STL in C++?
Problem Statement:
Given a vector, obtain the reverse of a vector using STL in C++.
Example
Input: {19, 35, 55, 121, 56, 42}
result : {42,56,121,55,35,19}
Input: {13, 74, 25, 49, 26, 2}
result : {2,26,49,25,74,13}
How to solve it:
Reversing can be achieved with the assistant of reverse() function implemented in STL algorithm library.
Syntax:
std::reverse(start_index, last_index);
it will reverse the original vector.
Implementation:
#include <iostream>
#include<vector>
#include<algorithm>
int main()
{
// Intialize the vector
std :: vector<int> a = {19, 35, 55, 121, 56, 42};
// reversing the vector
std::reverse(a.begin(),a.end());
// prining the reversed array
for(int i=0;i<a.size();i++){
std::<<a.at(i);
}
return 0;
}
Output:
42 56 121 55 35 19
Post a Comment: