Expert C++
上QQ阅读APP看书,第一时间看更新

Ranges

The ranges library provides a new way of working with ranges of elements. To use them, you should include the <ranges> header file. Let's look at ranges with an example. A range is a sequence of elements having a beginning and an end. It provides a begin iterator and an end sentinel. Consider the following vector of integers:

import <vector>

int main()
{
std::vector<int> elements{0, 1, 2, 3, 4, 5, 6};
}

Ranges accompanied by range adapters (the | operator) provide powerful functionality to deal with a range of elements. For example, examine the following code:

import <vector>
import <ranges>

int main()
{
std::vector<int> elements{0, 1, 2, 3, 4, 5, 6};
for (int current : elements | ranges::view::filter([](int e) { return
e % 2 == 0; })
)
{
std::cout << current << " ";
}
}

In the preceding code, we filtered the range for even integers using ranges::view::filter(). Pay attention to the range adapter | applied to the elements vector. We will discuss ranges and their powerful features in Chapter 7Functional Programming.