Q: c++ Iterate through vector with variable direction 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, 2, 3, 4};
    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 your stuff
    }

Does anyone know any better or nicer way to do this?

A: I would so something like this, using a standard library algorithm and reverse iterators where appropriate. For example,
void foo(int i) { /* do stuff */ }

if (smth)
  std::for_each(vec.begin(), vec.end(), foo);
else
  std::for_each(vec.rbegin(), vec.rend(), foo);


A: 
Does anyone know any better or nicer way to do this?

Yes: implement only the operation in the for loop body (everything between the accolades). Then, use std::for_each with a pair of iterators. The code is tested, stable and idiomatic:
old code:
std::vector<int> vec = {1, 2, 3, 4};
int direction = 1 // or -1;
int start = direction == 1 ?  0 : (int)arrs.size();
for (int i=start; i<(int)vec.size() && 0<=i; i+=direction) {
  // do your stuff
}

new code:
auto your_stuff = [](const int& i) { /* do your stuff */ };
// forward iteration:
std::for_each(vec.begin(), vec.end(), your_stuff);
// backward iteration:
std::for_each(vec.rbegin(), vec.rend(), your_stuff);


A: Your solution to this is quite neat for vector. There are some data structures where this kind of iteration would be too expensive, e.g. singly linked list. On the other hand, you always have STL container iterator to play with. I believe there is a back iterator as well.
