When I fill an std::vector
knowing in advance the final size, I usually reserve its capacity in advance to avoid reallocation of its content (which on C++03 involves calling copy constructors for each object already stored in the vector
).
This is a trivial example:
std::vector<std::string> v;
v.reserve(10);
for( std::vector<std::string>::size_type i = 0, capacity = v.capacity();
i < capacity;
++i )
{
v.push_back(std::to_string(i));
}
There's a better way (less C-style) to loop around the std::vector
capacity?
I'm looking for both C++03 and C++11 answers.
Edit: I rewrote the sample because all the answers and comments were going off topic, concerning only filling the std::vector with an array, which is not the point of the question.