cpp cpp - 1 year ago 90
C++ Question

Printing vector in reverse order

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

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());
reverse(vec.begin(), vec.end());

Answer Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download