I understand it’s a good practice to use “reserve” to avoid unnecessary reallocations (Item 14 of Effective STL):
std::vector<int> v1;
v1.reserve(1000);
for (int i = 0; i < 1000; i++)
v1.push_back(i);
Does the same rule apply when you call assign?
std::vector<int> v2;
//v2.reserve(v1.size()); // Better to do this?
v2.assign(v1.begin(), v1.end());
In case when
v1isstd::vectoryou don’t really need it, as the compiler/stl knows how many items are going to be there inv2(and willreservethe needed amount itself before copying the actual data).For the generic case, however, it may make sense to
reservethe needed amount in advance, if the input container (v1) doesn’t know how many items are there, and you have the number at hand.