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

C++ range/xrange equivalent in STL or boost?

Boost irange should really be the answer (ThxPaul Brannan) I’m adding my answer to provide a compelling example of very valid use-cases that are not served well by manual looping: #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/irange.hpp> using namespace boost::adaptors; static int mod7(int v) { return v % 7; } int main() { std::vector<int> v; boost::copy( …

Read more

Difference between Iterator and Spliterator in Java8

An Iterator is a simple representation of a series of elements that can be iterated over. eg: List<String> list = Arrays.asList(“Apple”, “Banana”, “Orange”); Iterator<String> i = list.iterator(); i.next(); i.forEachRemaining(System.out::println); #output Banana Orange A Spliterator can be used to split given element set into multiple sets so that we can perform some kind of operations/calculations on …

Read more

Class accessible by iterator and index

The current accepted answer from @Ignacio Vazquez-Abrams is sufficient. However, others interested in this question may want to consider inheriting their class from an abstract base class (ABC) (such as those found in the standard module collections.abc). This does a number of things (there are probably others as well): ensures that all of the methods …

Read more

What’s the use of yield break? [duplicate]

To give a code example, say you want to write an iterator that returns nothing if the source is null or empty. public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source) { if (source == null) yield break; foreach (T item in source) yield return item; } Without the yield break it becomes impossible to return an empty set inside …

Read more