Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct a vector with elements in-place

Tags:

c++

c++14

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.

like image 732
user4673882 Avatar asked Mar 16 '23 18:03

user4673882


1 Answers

You can use algorithm generate:

std::vector<std::unique_ptr<int>> v(10);
std::generate (v.begin(), v.end(), []() { return std::make_unique<int>(); });
like image 157
Christophe Avatar answered Mar 27 '23 10:03

Christophe