Search code examples
c++rangec++20

How will I pass ranges instead of iterator-pairs in C++20?


I've heard that C++20 will support acting on ranges, not just begin+end iterator pairs. Does that mean that, in C++20, I'll be able to write:

std::vector<int> vec = get_vector_from_somewhere();
std::sort(vec);
std::vector<float> halves; 
halves.reserve(vec.size());
std::transform(
    vec, std::back_inserter(halves),
    [](int x) { return x * 0.5; }
);

?


Solution

  • Almost, yes!

    You'll just need to use the std::ranges:: namespace instead of just std::; at least, this is what Eric Niebler says in his blog post. So, you would write:

    std::vector<int> vec = get_vector_from_somewhere();
    std::ranges::sort(vec);
    std::vector<float> halves; 
    halves.reserve(vec.size());
    std::ranges::transform(
        vec, std::back_inserter(halves),
        [](int x) { return x * 0.5; }
    );
    

    You can also have a look at the cppreference page on std::all_of (and none_of and any_of) for a detailed example of C++20-style <algorithm> code; but not all of these pages have been written in on cppreference.com .


    As @Barry notes, if we could use ranges::to (which we can't in C++20, but can in C++23) we can make that even simpler:

    std::vector<int> vec = get_vector_from_somewhere();
    std::ranges::sort(vec);
    auto halves = vec
        | std::ranges::view::transform([](int x){ return x * 0.5; }) 
        | ranges::to<std::vector<float>>;