I want to iterate through some std::vector
s in a for loop but depending on some conditions, the vectors shall be iterated either forward or backward. I thought, I could easily do it by using either normal iterators or reverse iterators like this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec{0, 1, 2, 3, 5, 6, 7};
bool reverse = true;
std::iterator<random_access_iterator_tag, int> it, end_it;
if (reverse) {
it = vec.rbegin();
end_it = vec.rend();
} else {
it = vec.begin();
end_it = vec.end();
}
for (; it != end_it; it++) {
cout << *it << ", ";
}
return 0;
}
But unfortunately vector::begin()
and vector::rbegin()
don't seem to be using the same parent class. Is there another way to do what I want without having two different loops in an if-else-structure? Of course I could create a function/lambda for the loop body or use some index arithmetic but is there a more elegant way?
The compiler complains about the assignment it = vec.begin()
as they are different types. gcc and VC++ output different errors and seem to use different types for the return values of vector::begin
.