Printing vector in reverse order

后端 未结 5 1272
粉色の甜心
粉色の甜心 2021-01-21 22:34

Is there a better way of printing a vector in reverse order then this:

#include
#include
#include
using namespace          


        
5条回答
  •  余生分开走
    2021-01-21 23:31

    There are many ways to do this.I will just explain one, more can be seen in this link.

    Using constant reverse iterator(crbegin):

    Reverse iterators iterate backward i.e increasing them moves them towards the beginning of the container.

    To check if we have reached beginning, we can use the iterator variable(x in my case) to compare with crend (returns the starting of the vector).Remember everything is reverse here!

    following is a simple implementation:

    for(auto x = vec.crbegin() ; x!=vec.crend() ; x++){
            cout<<*x<<" ";
    }
    

提交回复
热议问题