Junior
Are you familiar with resize and reserve methods?
sobes.tech AI
Answer from AI
Yes, I know.
In the context of standard C++ containers (for example, std::vector), the methods resize and reserve are used to manage the size and capacity of the container:
-
reserve(n): Requests that the vector's capacity be at leastn. Ifnis greater than the current capacity, new storage is allocated, and elements are moved there. Capacity can increase, but the size of the vector (the number of elements) does not change.reserveis used to avoid multiple reallocations when adding elements.#include <vector> int main() { std::vector<int> v; v.reserve(100); // Guarantee capacity of at least 100 // Size of v is still 0 // Adding elements up to the 100th will most likely not cause reallocation return 0; } -
resize(n): Changes the size of the vector ton.- If
nis less than the current size, elements after then-th are removed. - If
nis greater than the current size:- New elements are added to the end.
- If
resize(n, value)is called, new elements are initialized withvalue. - If
resize(n)is called, new elements are initialized with the default value for the element type (by calling the default constructor).
- The capacity of the vector may increase to accommodate new elements if necessary.
#include <vector> int main() { std::vector<int> v = {10, 20, 30}; v.resize(5); // Size becomes 5. Two new elements are added (initialized to 0 for int). // v now {10, 20, 30, 0, 0} v.resize(2); // Size becomes 2. Elements 30, 0, 0 are removed. // v now {10, 20} v.resize(6, 99); // Size becomes 6. Four new elements are added (initialized to 99). // v now {10, 20, 99, 99, 99, 99} return 0; } - If
Key differences:
reserve(n) |
resize(n) / resize(n, value) |
|
|---|---|---|
| What it changes | Capacity (capacity) | Size (size) |
| Number of elements | Does not change | Changes to n |
| Initialization | No initialization occurs | New elements are initialized (by default or with value) |
| Reallocation | May occur to reach capacity n |
May occur to reach size n |