C++

C++ std_reverse for Reversing a Vector

One way to reverse a vector in C++ is to use a vector iterator and iterate backwards. The disadvantage of this approach is that the original order of the vector remains the same. The std::reverse() from the C++ algorithm library can be used to reverse a vector resulting to a new order of the same vector.

In order to use std::reverse, the algorithm library has to be included into the program. This article shows how to reverse a vector using the reverse() function in the algorithm library of the C++ standard library. In C++, std means standard.

Syntax of std::reverse()

The syntax for this reverse() function is the prototype. It is:

template<class BidirectionalIterator>

constexpr void reverse(BidirectionalIterator first, BidirectionalIterator last);

The first argument is an iterator that points to the first element of the vector. The second argument is an iterator that points just beyond the last element of the vector. If the vector name is vec, then the iterator first is given by:

vec.begin()

and the iterator, last is given by:

vec.end()

Program to reverse a Vector

The following program reverses a vector, using standard-reverse() :

    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;

    vectorvec = {'V', 'W', 'X', 'Y', 'Z'};

    int main()
    {
        reverse(vec.begin(), vec.end());
for(int i=0; i<vec.size(); i++) {
cout<<vec[i] << ' ';
        }
cout<<endl;
        return 0;
    }

The output is:

Z Y X W V

The vector library had to be included, for the vector use.

Conclusion

One way to reverse a vector in C++, is just to use a vector iterator and iterate backwards. The disadvantage with this approach, is that, the original order of the vector remains the same. std::reverse() from the C++ algorithm library, can be used to reverse a vector; resulting in the reversed order, in the same vector.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.