Skip to content

Ranges

Ranges

The ranges library is an extension and generalization of the algorithms and iterator libraries that makes them more powerful by making them composable and less error-prone.

All algorithms that take iterator pairs have overloads that accept ranges (e.g ranges::sort).

The library creates and manipulates range views, lightweight objects that indirectly represent iterable sequences (ranges). Ranges are an abstraction on top of [begin, end) iterator pairs, e.g. ranges made by implicit conversion from containers.

The ranges library was originally developed as the
range-v3 library, and was finally merged to ISO C++ as of C++20. The range-v3 implementation is currently available on more compilers and platforms than the C++20 library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Ranges in C++20: https://en.cppreference.com/w/cpp/ranges
# Use range-v3 for now: https://github.com/ericniebler/range-v3
find_package(range-v3 QUIET)
if (NOT range-v3_FOUND)
    FetchContent_Declare(range-v3 URL https://github.com/ericniebler/range-v3/archive/0.11.0.zip)
    FetchContent_GetProperties(range-v3)
    if (NOT range-v3_POPULATED)
        FetchContent_Populate(range-v3)
        add_library(range-v3 INTERFACE IMPORTED)
        target_include_directories(range-v3 INTERFACE "${range-v3_SOURCE_DIR}/include")
    endif ()
endif()
add_executable(ranges ranges.cpp)
target_link_libraries(ranges PUBLIC range-v3)

1
#include <range/v3/all.hpp>

1
2
std::vector<double> v(30);
ranges::iota(v, 1);

1
std::cout << ranges::count(v, 0) << '\n';

1
std::cout << ranges::accumulate(v, 0) << '\n';

1
ranges::sort(v);

1
std::cout << ranges::binary_search(v, 15) << '\n';

1
std::cout << ranges::is_sorted(v) << '\n';

1
2
ranges::for_each(v, [](const int c) { std::cout << c << " "; });
std::cout << '\n';

1
2
3
std::array<int, 6> a{{0, 5, 2, 1, 3, 4}};
auto filtered_range = ranges::views::filter(a, [](int i) { return i > 2; });
std::vector<int> v2(filtered_range.begin(), filtered_range.end());

1
2
3
4
auto reversed_range = ranges::views::reverse(a);
for (int x : reversed_range) {
    std::cout << x << ' ';
}

1
2
3
4
5
ranges::sort(a);
auto unique_range = ranges::views::unique(a);
for (int x : unique_range) {
    std::cout << x << ' ';
}

1
2
3
4
5
6
7
8
std::map<std::string, int> m;
m["a"] = 0;
m["b"] = 1;
m["c"] = 2;
auto map_keys = ranges::views::keys(m);
for (const std::string &k : map_keys) {
    std::cout << k << ",";
}

1
2
3
4
5
6
7
std::string s = "The range v3 library";
std::regex expr{"[\\w+]+"};
auto tokenizer = ranges::views::tokenize(
    s, expr, 0, std::regex_constants::match_default);
for (auto &x : tokenizer) {
    std::cout << x << ",";
}

1
2
3
4
auto ir = ranges::views::ints(0, 3);
for (auto x : ir) {
    std::cout << x << ",";
}

Share Snippets