I am looking for the way to initialize a vector with the minimal amount of copy.
struct T {
std::vector<int> v;
//some stuff here ; pod
T(std::vector<int> vv):v(vv){}://a non default constructor
};
Now to initialize a vector, i do
std::vector<T> vec(n);
for (auto it = vec.begin() ;it != vec.end(),++it)
{
// do some stuff to *it;
}
the “do some stuff here” basically just redo what is done in the constructor, and so i have two initialization of T.v…
I also thought of doing
std::vector<T> vec;
for (int i = 0 ; i< n;++i)
{
std::vector<int> vv = // blabla
T t(vv);
vec.push_back(t);
}
which again result on vv being copied…
So how do i initialize a vector of struct, where each element is initialized using a non default constructor (call with different argument for each element) ?
Use
reserveand construct elements in place:You can also use the old-style
push_back(); with any luck, the compiler will optimize out several unneeded copies. You should probably also add an iterator-based and an initializer-list constructor toT, just to give you some flexibility.