C++ forward and reverse iteration through container

Viewed 2607

I was wondering if anyone had any thoughts on how to iterate through the elements of a vector (or container) when the direction of the iteration is input.

This was the first thing I could come up with:

std::vector<int> vec = {1, 5, 7, 23};
int direction = 1 // or -1;
int start = direction == 1 ?  0 : (int)arrs.size()-1;
for (int i=start; i<(int)vec.size() && 0<=i; i+=direction) {
    //do_stuff_fn(i, vec.at(i))
}

Does anyone know any better or nicer way to do this? And please I need to have access to the index i in the loop. I'm afraid that this means that the std::for_each is not an option.

4 Answers
Related