Reputation: 260
I have a struct Y
with a vector of type X
, I would like to ask whether in this case assign is the best solution or copy would be better? Should I resize y.xVec
?
#include <iostream>
#include <vector>
struct X {
X(int x):x_(x)
{}
int x_;
};
struct Y {
std::vector<X>xVec;
};
int main()
{
X x1(1);
X x2(2);
std::vector<X> v = {x1,x2};
Y y;
y.xVec.assign(v.begin(), v.end());
return 0;
}
Upvotes: 1
Views: 134
Reputation: 249552
The simplest code is the best here:
y.xVec = v;
Or if you don't need v
anymore:
y.xVec = std::move(v);
Or if you will use v
again but starting from empty:
y.xVec = std::exchange(v, {});
exchange()
is better than move()
if you need to use v
again, because it leaves v
in its default-constructed state (empty), rather than the unspecified state given by move()
.
Upvotes: 1