STL Vector Use
C++ c++ stl
Published: 2007-01-23
STL Vector Use

I recently wrote a piece of code that looked something like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
static const int NUM_TOTAL_VALUES = ...;
typedef ... T;

// Create vec and reserve NUM_TOTAL_VALUES spaces for later insertion
std::vector<T> vec(NUM_TOTAL_VALUES);

// Insert values into vec
for (int i = 0; i != NUM_TOTAL_VALUES; ++i)
    vec.push_back(...);

// vec should now have NUM_TOTAL_VALUES values in it (but doesn't!)

What’s wrong with this code?

The constructor vector(size_type _Count); does more than just allocate enough space to store _Count items — it also inserts _Count (default constructed) items into the vector. To reserve space without actually inserting values, use reserve():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static const int NUM_TOTAL_VALUES = ...;
typedef ... T;

std::vector<T> vec;
vec.reserve(NUM_TOTAL_VALUES);

for (int i = 0; i != NUM_TOTAL_VALUES; ++i)
    vec.push_back(...);

// vec now has NUM_TOTAL_VALUES values in it, as intended.