5.2 Vector

Additionally to the member functions described in section 4.1.1, a reserve member function is provided, which informs the vector of a planned change in size. This enables the vector to manage the storage allocation accordingly. reserve does not change the size of the vector and reallocation happens if and only if the current capacity is less than the argument of reserve.


void reserve(size_type n);

After a call of reserve, the capacity (i.e. the allocated storage) of the vector is greater or equal to the argument of reserve if reallocation has happened, equal to its previous value otherwise. This means, that if you use reserve with a value greater than the actual value of capacity, reallocation happens and afterwards, the capacity of the vector is greater or equal to the value given as argument to reserve.

To make it clear, why such a member function is provided, remember that reallocation invalidates all the references, pointers and iterators referring to the elements in the sequence. The use of reserve guarantees that no reallocation takes place during the insertions that happen after a call of reserve until the time when the size of the vector reaches the capacity caused by the call of reserve.

With this in mind, take a look at exercise 4.1.1. We decided to use a list for storing the single "bits", because inserting into a list never invalidates any of the iterators to this container, which was essential for the bit-stuff algorithm to work. Now, knowing of the existence of reserve, we can use this member function to reserve a certain vector capacity and are so in a position to use a vector as well. After the call of reserve, we can insert elements into the vector till capacity is reached being sure that no reallocation will happen. The argument n of reserve has to be computed by considering a maximum number of bits to be bit-stuffed and the worst case expansion, which happens when bit-stuffing a sequence only consisting of 1's.

Continue with section 5.3

Back to index


Johannes Weidl (J.Weidl@infosys.tuwien.ac.at) - Apr 16, 1996