Last updated:2026-10-12
C++ vector resize vs reserve¶
In C++, resize and reserve are two member functions of containers (for example std::vector) used to manage a vector's size and memory allocation.
For example:
std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl; //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1
std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl; //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1
The resize function changes the size of the container; it can increase or decrease the number of elements in the container. When the container's size is increased, the newly added elements are initialized. When the size is decreased, elements beyond the new size are removed.
The reserve function pre-allocates the container's memory without changing its size. It can be used to allocate enough memory in advance, avoiding frequent reallocation and thereby improving performance. Note, though, that calling reserve does not change the container's size — it only allocates enough memory space for the container.
It is worth noting that resize and reserve differ in which container types they are available on. The resize function is available for most container types, while reserve is only valid for containers with dynamic size, such as std::vector and std::deque. For fixed-size container types (such as std::array), calling reserve has no effect.
From the source-code level:
void resize(size_type new_size, value_type value = value_type()) {
if (new_size < size()) {
erase(begin() + new_size, end()); // 移除超出新大小的元素
} else {
insert(end(), new_size - size(), value); // 添加新元素
}
}
void reserve(size_type _n) {
if (__n > max_size())
__throw_length_error(__N("vector::reserve"));
if (capacity() < __n)
_M_reallocate(__n);
}
End of this section
Related Topics¶
- C++ Pure Virtual Functions and Abstract Classes | C++那些事
- C++ assert | C++那些事
- C++ Bit Fields | C++那些事
- Implementing C++ Polymorphism in C | C++那些事
- C++ const Constants and Qualifiers | C++那些事
- The Complete C++ const Family | C++那些事
- C++ Dereference Operator * | C++那些事
- C++ Initialization and Assignment | C++那些事
- Ways to Return Multiple Values in C++ | C++那些事
- C++ mutable Keyword | C++那些事