C++ forward and reverse iteration through container

ormurin

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.

V-X

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Has many through in reverse?

From Dev

complicated iteration through a dictionary

From Dev

Iteration through XML?

From Dev

How forward and reverse DNS works

From Dev

Simplify container iteration using lambdas

From Dev

Is there any best way(math / C++ trick) of Iterate through forward and reverse within a give range

From Dev

`forever`: How to forward information to next iteration?

From Dev

nested generic container iteration C++

From Dev

In C, how to improve iteration through list?

From Dev

Modify reverse lookup with forward lookup

From Dev

c++ : double iteration through map

From Dev

Unordered Iteration of a Container

From Dev

Sequence of Number, through Iteration

From Dev

Custom iteration through array in C printing every nth value

From Dev

C++ map erase using forward and reverse iterators

From Dev

Generating components through iteration

From Dev

Get count through iteration

From Dev

Advanced Iteration through an Array

From Dev

Reverse Iteration of an STL Algorithm

From Dev

Simplify container iteration using lambdas

From Dev

nested generic container iteration C++

From Dev

Unordered Iteration of a Container

From Dev

C++ map erase using forward and reverse iterators

From Dev

Generating components through iteration

From Dev

Iteration through an array

From Dev

Iteration through hex string

From Dev

What's the forward and reverse zooming?

From Dev

C++: Forward iterator interface of a member container to class interface

From Dev

Iterate through Queue in c# while Dequeue for each iteration