Skip to content

Ad hoc range helpers

Raymond Chen edited this page Jun 1, 2019 · 2 revisions

The ad-hoc range helpers assist in creating range-based for loops.

Usage

The ad-hoc range helpers are defined in wil/common.h.

#include <wil/common.h>

wil::make_range

template<typename T> auto make_range(T begin, T end);        // (1)
template<typename T> auto make_range(T begin, size_t count); // (2)

The make_range function returns a helper object (of unspecified type) that can be used by a range-based for loop.

  • T
    (1) A type which satisfies the requirements of an input iterator.
    (2) A type which satisfies the requirements of a random access iterator.
    In practice, T is usually a pointer type.

Version (1) iterates over the range [begin, end).

Version (2) iterates over the range [begin, begin + count).

The unspecified type has the following methods:

  • T begin() returns begin.
  • T end() returns (1) end or (2) begin + count.

Examples

std::vector<int> data = { 1, 1, 2, 3, 3, 4, 5, 5, 6 };
 
auto lower = std::lower_bound(data.begin(), data.end(), 2);
auto upper = std::upper_bound(data.begin(), data.end(), 4);

// prints 2 3 3 4
for (auto& value : wil::make_range(lower, upper))
{
    std::cout << value << " ";
}

int array[] = { 1, 2, 3, 4, 5 };

// prints 2 3 4
for (auto& value : wil::make_range(&array[1], 3))
{
    std::cout << value << " ";
}