Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a C++ container using a (lambda) function?

I want to initialize a container with pointers to objects. I currently have a loop like this:

for(int i=0;i < n;i++) {
    container.push_back(new Object());
}

Which C++ operation (i.e. similar to std::transform) is the right to replace this loop and initialize a container with n newly created objects?

like image 257
allo Avatar asked Jul 12 '18 13:07

allo


People also ask

Is there Lambda function in C?

Significance of Lambda Function in C/C++ Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store.

Does AWS Lambda use containers?

Lambda supports only Linux-based container images. Lambda provides multi-architecture base images. However, the image you build for your function must target only one of the architectures. Lambda does not support functions that use multi-architecture container images.


2 Answers

You could use std::generate_n and std::back_inserter with lambda.

std::generate_n(std::back_inserter(container), n, [] { return new Object(); });
like image 30
songyuanyao Avatar answered Sep 17 '22 16:09

songyuanyao


Use std::generate:

constexpr int n = 10;
std::vector<Object*> v1(n);
std::generate(v1.begin(), v1.end(), [](){ return new Object(); });

or std::generate_n:

std::vector<Object*> v2;
v2.reserve(n); // pre-allocate sufficient memory to prevent re-allocations
               // (you should have done in original loop approach as well)
std::generate_n(std::back_inserter(v2), n, [] { return new Object(); });
like image 186
Ron Avatar answered Sep 17 '22 16:09

Ron