Iterating C++ vector from the end to the beginning

One way is: for (vector<my_class>::reverse_iterator i = my_vector.rbegin(); i != my_vector.rend(); ++i ) { } rbegin()/rend() were especially designed for that purpose. (And yes, incrementing a reverse_interator moves it backward.) Now, in theory, your method (using begin()/end() & –i) would work, std::vector‘s iterator being bidirectional, but remember, end() isn’t the last element — it’s one … Read more

Creating my own Iterators

/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I’m letting the code below stand because it can be useful in similar circumstances. Is an own iterator actually necessary here? Perhaps it’s sufficient to forward all required definitions to the container holding the actual Points: // Your class … Read more

Can iterators be reset in Python?

I see many answers suggesting itertools.tee, but that’s ignoring one crucial warning in the docs for it: This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use … Read more

Circular list iterator in Python

Use itertools.cycle, that’s its exact purpose: from itertools import cycle lst = [‘a’, ‘b’, ‘c’] pool = cycle(lst) for item in pool: print item, Output: a b c a b c … (Loops forever, obviously) In order to manually advance the iterator and pull values from it one by one, simply call next(pool): >>> next(pool) … Read more

What’s the best way to iterate over two or more containers simultaneously

Rather late to the party. But: I would iterate over indices. But not with the classical for loop but instead with a range-based for loop over the indices: for(unsigned i : indices(containerA)) { containerA[i] = containerB[i]; } indices is a simple wrapper function which returns a (lazily evaluated) range for the indices. Since the implementation … Read more

what is the difference between const_iterator and iterator? [duplicate]

There is no performance difference. A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness. When you have a const reference to the container, you can only get a … Read more

Using map() on an iterator

The simplest and least performant way to do this is: Array.from(m).map(([key,value]) => /* whatever */) Better yet Array.from(m, ([key, value]) => /* whatever */)) Array.from takes any iterable or array-like thing and converts it into an array! As Daniel points out in the comments, we can add a mapping function to the conversion to remove … Read more