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.
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.
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.
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With