std::vector<T,Allocator>::reserve (3) - Linux Manuals
std::vector<T,Allocator>::reserve: std::vector<T,Allocator>::reserve
NAME
std::vector<T,Allocator>::reserve - std::vector<T,Allocator>::reserve
Synopsis
void reserve( size_type new_cap );
Increase the capacity of the vector to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), new storage is allocated, otherwise the method does nothing.
reserve() does not change the size of the vector.
If new_cap is greater than capacity(), all iterators, including the past-the-end iterator, and all references to the elements are invalidated. Otherwise, no iterators or references are invalidated.
Parameters
new_cap - new capacity of the vector
Type requirements
-
T must meet the requirements of MoveInsertable.
Return value
(none)
Exceptions
* std::length_error if new_cap > max_size().
* any exception thrown by Allocator::allocate() (typically std::bad_alloc)
If an exception is thrown, this function has no effect (strong_exception_guarantee).
If T's move constructor is not noexcept and T is not CopyInsertable into *this, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified. (since C++11)
Complexity
At most linear in the size() of the container.
Notes
Correctly using reserve() can prevent unnecessary reallocations, but inappropriate uses of reserve() (for instance, calling it before every push_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usually not call reserve() on the vector, since it does not know of the vector's usage characteristics.
When inserting a range, the range version of insert() is generally preferable as it preserves the correct capacity growth behavior, unlike reserve() followed by a series of push_back()s.
reserve() cannot be used to reduce the capacity of the container; to that end shrink_to_fit() is provided.
Example
// Run this code
Possible output:
See also
capacity (public member function)