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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With