×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

How to reverse vector elements in C++ STL?

C++ STL | reversing vector elements: Here, we are going to learn how to reverse elements of a vector using C++ STL program?
Submitted by IncludeHelp, on May 18, 2019

Given a vector and we have to reverse their element using C++ STL program.

Reverse a vector

To reverse vector elements, we can use reverse() function which is defined in <algorithm> header in C++ standard template library. It accepts the range of the iterators in which reverse operation to be performed and reverses the elements between the given range.

Note: To use vector – include <vector> header, and to use reverse() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

Syntax

reverse(iterator start, iterator end);

Here, start_position, iterator end_position are the iterators pointing to the start and end elements in a container to be reversed.

Example

Input:
vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };

reverse(v1.begin(), v1.end());
    
Output:
15, 25, 50, 40, 30, 20, 10

C++ STL program to reverse vector elements

//C++ STL program to reverse vector elements 
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "before reversing vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //reversing vector's all elements
    reverse(v1.begin(), v1.end());

    //printing elements
    cout << "after reversing vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

before reversing vector elements...
10 20 30 40 50
after reversing vector elements...
50 40 30 20 10

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.