python arbitrarily incrementing an iterator inside a loop

There is a fantastic package in Python called itertools. But before I get into that, it’d serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the __iter__() class method that provides an iterator type. “Understanding Python’s ‘for’ statement” is a nice … Read more

How to remove constness of const_iterator?

There is a solution with constant time complexity in C++11: for any sequence, associative, or unordered associative container (including all of the Standard Library containers), you can call the range-erase member function with an empty range: template <typename Container, typename ConstIterator> typename Container::iterator remove_constness(Container& c, ConstIterator it) { return c.erase(it, it); } The range-erase member … Read more

For-each vs Iterator. Which will be the better option

for-each is syntactic sugar for using iterators (approach 2). You might need to use iterators if you need to modify collection in your loop. First approach will throw exception. for (String i : list) { System.out.println(i); list.remove(i); // throws exception } Iterator it=list.iterator(); while (it.hasNext()){ System.out.println(it.next()); it.remove(); // valid here }

Why no emplacement iterators in C++11 or C++14?

Is there any technical reason we couldn’t have front_emplacer, back_emplacer, and emplacer? No, there is no technical reason. As proof, here is a complete implementation of back_emplacer with a demo of your Use Case 1… #include <iterator> #include <vector> #include <iostream> template<class Container> class back_emplace_iterator : public std::iterator< std::output_iterator_tag, void, void, void, void > { … Read more

Generator functions equivalent in Java

Had the same need so wrote a little class for it. Here are some examples: Generator<Integer> simpleGenerator = new Generator<Integer>() { public void run() throws InterruptedException { yield(1); // Some logic here… yield(2); } }; for (Integer element : simpleGenerator) System.out.println(element); // Prints “1”, then “2”. Infinite generators are also possible: Generator<Integer> infiniteGenerator = new … Read more