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

  • A+

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?


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(); }); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: