Chaining iterators for C++

Came across this question while investigating for a similar problem. Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the Boost.Range library. It features a join-function, which can join two ranges into a single one. Here you might incur performance penalties, … Read more

How to check that the passed Iterator is a random access iterator?

If Iterator is a random access iterator, then std::iterator_traits<Iterator>::iterator_category will be std::random_access_iterator_tag. The cleanest way to implement this is probably to create a second function template and have Foo call it: template <typename Iterator> void FooImpl(Iterator first, Iterator last, std::random_access_iterator_tag) { // … } template <typename Iterator> void Foo(Iterator first, Iterator last) { typedef typename … Read more

Python for loop and iterator behavior

Your suspicion is correct: the iterator has been consumed. In actuality, your iterator is a generator, which is an object which has the ability to be iterated through only once. type((i for i in range(5))) # says it’s type generator def another_generator(): yield 1 # the yield expression makes it a generator, not a function … Read more

C++ template typename iterator

In list<tNode<T>*>::iterator, you have a dependant name, that is, a name that depends on a template parameter. As such, the compiler can’t inspect list<tNode<T>*> (it doesn’t have its definition at this point) and so it doesn’t know whether list<tNode<T>*>::iterator is either a static field or a type. In such a situation, the compiler assumes that … 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

What is the reason behind cbegin/cend?

It’s quite simple. Say I have a vector: std::vector<int> vec; I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to std::for_each: std::for_each(vec.begin(), vec.end(), SomeFunctor()); In C++03, SomeFunctor was free to be able to modify the parameter it gets. Sure, SomeFunctor could take its parameter … Read more

tech