Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing std::vector from resizing on push_back

Tags:

c++

stl

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?

like image 599
J Cooper Avatar asked Dec 09 '22 07:12

J Cooper


1 Answers

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
like image 92
Etienne de Martel Avatar answered Dec 26 '22 00:12

Etienne de Martel