I have a vector of smart pointers. So far I can construct them in a loop like this:
std::vector<std::unique_ptr<int>> v(10);
for (int i = 0; i < 10; ++i)
v.emplace_back(std::make_unique<int>());
I don't want to do this though. I want something like the following:
std::vector<std::unique_ptr<int>> v(10, std::make_unique<int>());
This does not work. It seems like vector only has a constructor that will create copies or default-insert. So can I accomplish this? If the answer is no, what is the reasoning? In the future I would like to see a constructor that will allow the above.
You can use algorithm generate:
std::vector<std::unique_ptr<int>> v(10);
std::generate (v.begin(), v.end(), []() { return std::make_unique<int>(); });
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