Home »
        C++ STL
    
    Printing all elements in reverse order of a vector in C++ STL
    
    
    
    
    
    
        C++ STL | printing all elements of a vector in reverse order: Here, we are going to learn how to print all elements of a vector in reverse order using vector::begin() and vector::end() function in C++ STL?
        
            Submitted by IncludeHelp, on May 09, 2019
        
    
    Printing all elements of a vector in reverse order
    To print all elements of a vector in reverse order, we can use two functions 1) vector::begin() and vector::end() functions.
    vector::begin() function returns an iterator pointing to the first elements of the vector.
    vector::end() function returns an iterator point to past-the-end element of the vector.
    We run a loop from past-the-element to the first elements of the vector elements.
    
    Note: To use vector, include <vector> header.
    
        
    C++ STL program to print all elements of a vector in reverse order
//C++ STL program to print all elements 
//of a vector in reverse order
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> v1;
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);
    //creating iterator
    vector<int>::iterator it;
    //printing all elements
    cout << "vector v1 elements are in reverse order : " << endl;
    for (it = v1.end() - 1; it >= v1.begin(); it--)
        cout << *it << " ";
    cout << endl;
    return 0;
}
Output
vector v1 elements are in reverse order :
50 40 30 20 10
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement