How to copy map, filter and reduce behavior in C ++ using STL?

I assume that we can use std :: transform to replicate map behavior in C ++ as follows:

std::vector<int> in = { 1 , 2 , 3 ,4 }; std::vector<int> out(in.size()); std::transform(in.being() , in.end() , out.begin() , [](const int & val) { return val+1; }); 

I guess it's better to use a spin insert.

 std::vector<int> out2; std::transform(in.begin() , in.end() , std::back_inserter(out2) , [](const int & val){ return val + 1; }); // out will be { 2 , 3 ,4 ,5 } 

I'm right? How to make a filter and reduce operations in C ++ using STL?

+9
source share
2 answers

Depends on the container you use.

std::back_inserter will only work if the container has a push_back function.

For example, back_insterter cannot be used with forward_list .

In this case, we need to allocate memory before we call it std::transform , and the first approach is better.

0
source

You can use std::transform to display and std::copy_if to filter.

You have two options for reducing depending on your input and on whether you want to use a particular type of execution model. I wrote some simple examples below to demonstrate common use cases. Please note that there are many overloads for all of these algorithms, which you should use depending on your needs.


  1. std::transform

Squaring the vector of integers:

 std::vector<int> nums{1,2,3,4}; auto unary_op = [](int num) {return std::pow(num, 2);}; std::transform(nums.begin(), nums.end(), nums.begin(), unary_op); // nums: 1, 4, 9, 16 
  1. std::copy_if

Filtering odd numbers only by integer vector:

 std::vector<int> nums{1,2,3,4}; std::vector<int> odd_nums; auto pred = [](int num) {return num & 1;}; std::copy_if(nums.begin(), nums.end(), std::back_inserter(odd_nums), pred); // odd_nums: 1, 3 
  1. std::reduce

The sum of integers in a vector, starting at 0 using a parallel execution model. This is really useful if, for example, you are performing a reduction operation on a really large list. Consider that the binary operator in this case ("+") is associated and commutative, otherwise the behavior would be non-deterministic. This is really important. The reduction operation does not work if the execution model is not consistent. Available only with C ++ 17.

 std::vector<int> nums{1,2,3,4}; auto binary_op = [](int num1, int num2){return num1 + num2;}; int result = std::reduce(std::execution::par, nums.begin(), nums.end(), 0, binary_op); // result: 10 
  1. std::accumulate

The same as Reduce, except that it does not support the execution model, and the Reduce operation is performed in order.

 std::vector<int> nums{1,2,3,4}; auto binary_op = [](int num1, int num2){return num1 + num2;}; int result = std::reduce(std::execution::par, nums.begin(), nums.end(), 0, binary_op); // result: 10 
0
source

Source: https://habr.com/ru/post/1260620/


All Articles