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

2.2k views Asked by At

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 . I understand how the transformations work, but does 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.

1

There are 1 answers

4
Jarod42 On BEST ANSWER

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;