Views

Contents

Views#

Views are a special type of range—it does not own its own data, and it is lazy—it generates the data as needed.

iota#

A nice example of this is std::views::iota. This generates integers in increasing order from a beginning value up to (but not including the end value). E.g.,

std::views::iota(0, 5)

would give the numbers 0, 1, 2, 3, and 4.

We can use this in a for-loop:

Listing 92 iota.cpp#
#include <iostream>
#include <ranges>

int main() {

    for (auto e : std::views::iota(0, 5)) {
        std::cout << e << std::endl;
    }

}

Reverse loop#

We can loop over a vector in reverse using std::views::reverse.

Listing 93 reverse.cpp#
#include <iostream>
#include <vector>
#include <ranges>

int main() {

    std::vector<int> vec{1, 2, 4, 8, 16};

    for (auto e : std::views::reverse(vec)) {
        std::cout << e << std::endl;
    }

}

Note

An alternate way to do this is to use a range adaptor of the form:

for (auto e : v | std::views::reverse) {
    std::cout << e << std::endl;
}

With range adaptors, you can chain a lot of them together to create complex views into the data.