Preventing std::vector from resizing on push_back
I have a std::vector that I know will never have to grow--it will always have n
elements (开发者_运维问答unfortunately, n
isn't known at compile time so I can't use std::array). I can do:
std::vector<blah> v(n);
Which correctly sets its capacity to n
. But when I proceed to fill v
with push_back
, it automatically resizes to 2n
.
I realize this is premature optimization, but it's bugging me. Is there a way to set max size or something?
That constructor does not sets the capacity of the vector to n
, but insteads creates a vector containing n
objects constructed with blah
's default constructor. This can be confusing for people with a Java or .NET background, where ArrayList
and List<T>
both have a constructor that sets an initial capacity.
The solution is to do it in two steps:
std::vector<blah> v; // create an empty vector
v.reserve(n); // increase capacity
精彩评论