Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy std::vector but apply lambda to each element

I have got a std::vector X of std::vector of, say, double in C++.

How can I transform X into a std::vector Y of int such that X[i].size() == Y[i] holds for all admissible indices i?

std::vector< std::vector<int> > X;
...
/* What I want to do should look as follows */
std::vector<int> Y = std::copy_and_transform( X, lambda_to_get_size );

Of course, this can be realized with a loop, but in C++11 we would like to use lambdas instead. I have not found anything like that in std::algorithm. The standard tools seem to only give in place transformations that change the original vector and which do not allow changing the data type.

like image 283
shuhalo Avatar asked May 27 '17 09:05

shuhalo


People also ask

How to print a vector using a lambda function?

The lambda function take a variable * and increments it everytime. Using mutable so that the value of the * variable is preserved accross invocations of lambda.*/ std::generate (v.begin (), v.end (), [n = 0] () mutable { n = n + 5; return n;}); /* Print the vector using a lambda function.

How to copy elements of first vector into second vector in Python?

Make a for loop to copy elements of first vector into second vector by Iterative method using push_back (). Print the elements of v1. Print the elements of v2. End. Begin Initialize a vector v1 with its elements.

How to copy values from one vector to another in C++?

It is a simple way to copy values from vector 1 to vector 2 Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assignment operator “=” to copy the elements of v1 to v2. Print the elements of v1. Print the elements of v2. End. Begin Initialize a vector v1 with its elements.

How to copy elements of V1 to V2 in C++?

Call assign () to copy the elements of v1 to v2. Print the elements of v1. Print the elements of v2. End. Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assignment operator “=” to copy the elements of v1 to v2. Print the elements of v1. Print the elements of v2. End.


1 Answers

You can use std::transform:

std::vector<int> Y;
std::transform(X.cbegin(), X.cend(), std::back_inserter(Y), [](const std::vector<int>& value) {
    return value.size();
});
like image 162
Rakete1111 Avatar answered Sep 19 '22 16:09

Rakete1111