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

How to select a random element in std::set?

You could use the std::advance method. #include <set> #include <algorithm> int main() { using namespace std; // generate a set… set<int> s; for( int i = 0; i != 10; ++i ) s.insert(i); auto r = rand() % s.size(); // not _really_ random auto n = *select_random(s, r); } Where template<typename S> auto select_random(const S … 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

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

External Iterator vs Internal Iterator

External Iterator When you get an iterator and step over it, that is an external iterator for (Iterator iter = var.iterator(); iter.hasNext(); ) { Object obj = iter.next(); // Operate on obj } Internal Iterator When you pass a function object to a method to run over a list, that is an internal iterator var.each( … Read more

Does readlines() return a list or an iterator in Python 3?

The readlines method doesn’t return an iterator in Python 3, it returns a list Help on built-in function readlines: readlines(…) Return a list of lines from the stream. To check, just call it from an interactive session – it will return a list, rather than an iterator: >>> type(f.readlines()) <class ‘list’> Dive into Python appears … Read more