Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing vector in reverse order

Tags:

c++

stl

vector

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

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

void print_elem(int elem)
{
    cout << elem << endl;    
}

int main()
{
    int ia[4]={1,2,3,4};
    vector<int> vec(ia,ia+4);
    reverse(vec.begin(), vec.end());
    for_each(vec.begin(),vec.end(),print_elem);
    reverse(vec.begin(), vec.end());
}
like image 816
cpp Avatar asked Mar 20 '26 03:03

cpp


2 Answers

You can use the reverse iterators:

for_each(vec.rbegin(),vec.rend(),print_elem);
like image 134
Vaughn Cato Avatar answered Mar 21 '26 18:03

Vaughn Cato


There are many ways to print a bidirectional sequence in reverse without reversing the elements, e.g.:

std::copy(vec.rbegin(), vec.rend(), std::ostream_iterator<int>(std::cout, "\n"));
std::reverse_copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
like image 25
Dietmar Kühl Avatar answered Mar 21 '26 18:03

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!