Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

range

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; }
);

?

like image 738
einpoklum Avatar asked May 10 '19 18:05

einpoklum


1 Answers

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 .

like image 200
einpoklum Avatar answered Oct 21 '22 05:10

einpoklum