This informs the vector of a planned increase in size, although notice that the parameter n informs of a minimum, so the resulting capacity may be any capacity equal or larger than this.
When n is greater than the current capacity, a reallocation is attempted during the call to this function. If successful, it grants that no further automatic reallocations will happen because of a call to vector::insert or vector::push_back until the vector size surpasses at least n (this preserves the validity of iterators on all these future calls).
A reallocation invalidates all previously obtained iterators, references and pointers to elements of the vector.
In any case, a call to this function never affects the elements contained in the vector, nor the vector size (for that purposes, see vector::resize or vector::erase, which modify the vector size and content).
Parameters
- n
- Minimum amount desired as capacity of allocated storage.
Member type size_type is an unsigned integral type.
Return Value
noneIf the requested size to allocate is greater than the maximum size (vector::max_size) a length_error exception is thrown.
In case of reallocation, this is performed using Allocator::allocate(), which may throw its own exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Example
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
This example reserves enough capacity in a vector of ints to store the content of an entire file, which is then read character by character (each character stored as an element in the vector). By reserving a capacity for the vector of at least the size of the entire file, we avoid all the automatic reallocations that the object content could suffer each time that a new element surpassed the size of its previously allocated storage space.
Complexity
Linear at most.See also
| string::capacity | Return size of allocated storage (public member function) |
| string::resize | Resize string (public member function) |
| string::max_size | Return maximum size of string (public member function) |
