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.
Aucun commentaire:
Enregistrer un commentaire