Skip to content

cpppatterns Range-based algorithms

#include <iterator>
#include <utility>
template<typename ForwardRange>
void algorithm(ForwardRange& range)
{
    using std::begin;
    using std::end;
    using iterator = decltype(begin(range));
    iterator it_begin = begin(range);
    iterator it_end = end(range);
    // Now use it_begin and it_end to implement algorithm
}

INTENT

Implement algorithms that can be applied to any generic range of elements.

DESCRIPTION

On lines 12–13, we call begin and end on the range to get the respective iterators to the beginning and end of the range. We use using-declarations on lines 7–8 to allow these calls to be found via argument-dependent lookup before using the standard std::begin and std::end functions. With these iterators, we can now implement the algorithm over the elements between them.

If the iterators are not necessary to implement the algorithm, we may instead be able to use a simple range-based for loop.

NOTE: 在下面文章中,描述了ADL:

  • C++\Language-reference\Functions\Function-calls\ADL\ADL.md
  • C++\Language-reference\Classes\The-interface-principle.md