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?
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.
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.
You could use std::generate_n
and std::back_inserter
with lambda.
std::generate_n(std::back_inserter(container), n, [] { return new Object(); });
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(); });
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