Home » C++ STL

Printing all elements in reverse order of a vector using vector::begin() and vector::end() functions 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.