Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transform a vector into a new vector using range-v3?

I am coming from the C# world where I can write something like:

var newList = oldList.Select(x => x * 2).Where(x => x > 3).ToList();

This allows me to take a list, transform it in some way, and store the result in a new list.

I would like to do the same in C++ using range-v3. I understand how the transformations work, but does range-v3 provide similar "sink" methods for computing and collecting the results?

I am looking for something like toVector, which would compute a resulting range into a freshly allocated std::vector.

like image 609
sdgfsdh Avatar asked Jan 05 '17 16:01

sdgfsdh


1 Answers

You may do:

std::vector<int> v2 = v
                    | ranges::view::transform([](int x) { return x * 2; })
                    | ranges::view::filter([](int x) { return x > 3; });

Demo

Or, if you prefer auto on the left:

auto v2 = v 
        | ranges::view::transform([](int x) { return x * 2; }) 
        | ranges::view::filter([](int x) { return x > 3; }) 
        | ranges::to_vector;
like image 177
Jarod42 Avatar answered Sep 20 '22 13:09

Jarod42