Is it possible to construct a std::vector with an initial size and have it's elements in-place constructed? My stored type is not copyable so this doesn't work because the initial value is constructed as a temporary and copied to the elements:
#include <iostream>
#include <memory>
#include <vector>
struct A
{
A(int i = 0) : i_ (i) {};
int i_;
std::unique_ptr<int> p_; // not copyable
};
int main()
{
std::vector<A> v (10, 1); // error
}
This is close to what I'm trying to achieve and maybe it isn't so bad, but I'm wondering if there is a cleaner way:
int main()
{
//std::vector<A> v (10, 1); // error
std::vector<A> v;
v.reserve (10);
for (int i = 0; i < 10; ++i) {
v.emplace_back (1);
}
}
I'm limited to c++11 but I'm interested in c++17 solutions as well out of curiosity.
You could use std::generate_n
:
auto generator = []() {
return A(1);
};
std::vector<A> v;
v.reserve(10);
std::generate_n(std::back_inserter(v), 10, generator);
Your loop solution looks like the best way.
There's no built-in way to create a vector with N
(for N>1
) emplace-constructed elements.
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