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 containingnobjects constructed withblah‘s default constructor. This can be confusing for people with a Java or .NET background, whereArrayListandList<T>both have a constructor that sets an initial capacity.The solution is to do it in two steps: