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<int> v;
v.reserve(10);
std::vector<int>::size_type capacity = v.capacity();
for( std::vector<int>::size_type i = 0; i < capacity; ++i )
{
v.push_back(i);
}
There's a better way 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 answer and comments where going off topic, concerning only filling the std::vector with an array, which is not the point of the question.
Aucun commentaire:
Enregistrer un commentaire