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.
Since you want to use c++ and std library, there is nothing more suitable than reverse_iterator.
example:
std::vector<int> vec = {1, 5, 7, 23};
int direction = 1 // or -1;
auto begin = (direction > 0) ? vec.begin() : ver.rbegin();
auto end = (direction > 0) ? vec.end() : ver.rend();
for (auto it = begin; it != end; it++)
{
do_stuff_fn(it - vec.begin(), *it);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments