Is there a better way of printing a vector in reverse order then this:
#include
#include
#include
using namespace
You can use the reverse iterators:
for_each(vec.rbegin(),vec.rend(),print_elem);
Use reverse_iterator
instead of iterator
int main()
{
int ia[4]={1, 2, 3, 4};
vector<int> vec(ia,ia+4);
for(vector<int>::reverse_iterator it = vec.rbegin; it != vec.rend(); ++it)
{
std::cout << *it << std::endl;
}
}
The output will be: 4, 3, 2, 1
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"));
In C++20 you can utilize views::reverse found in ranges library and supported by gcc 10.
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector V{0, 1, 2, 3, 4, 5, 6, 7};
for (auto v : V | std::views::reverse)
{
std::cout << v << " ";
}
return 0;
}
And the output is:
7 6 5 4 3 2 1 0
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<<" ";
}