cpp cpp - 9 days ago 6
C++ Question

Printing vector in reverse order

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());
}

Answer

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"));