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());
}
You can use the reverse iterators:
for_each(vec.rbegin(),vec.rend(),print_elem);
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With