-
Notifications
You must be signed in to change notification settings - Fork 239
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.
The ad-hoc range helpers are defined in wil/common.h
.
#include <wil/common.h>
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()
returnsbegin
. -
T end()
returns (1)end
or (2)begin + count
.
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 << " ";
}