![]() |
In C++, vectors are dynamically resizable arrays provided by STL. They can automatically change their size according to the number of elements and users also can change its size using the std::vector::resize()and std::vector::reserve(). But there is some difference in how these functions works. In this article, we will learn what are the differences between the vector resize() and reserve() functions and which one should we use in differenct scenarios. PrerequisiteBefore discussing the main topic, we first need to know the difference between the vector size and vector capacity.
std::vector::resize()The resize() function changes the size of the vector. This operation adjusts the number of elements in the vector to the specified size. Syntaxvoid resize(size_type count);
void resize(size_type count, const T& value); How std::vector::resize() works?When resize() is called, you pass the new size as a parameter to which you would like the vector to get resized.
When to use the std::vector::resize()?We would use resize() whenever we were changing the actual number of elements held in the vector. This is a good thing because suppose the size was known exactly beforehand, or let’s just say, you knew you were going to drive that many elements later in the program depending upon the logic of the program. Example
Output Size of vector after resize(5): 5 Elements of vector after resize(5): 0 0 0 0 0 Size of vector after resize(3, 100): 3 Elements of vector after resize(3, 100): 0 0 0 Time Complexity: O(n) where n is the new size of the vector. std::vector::reserve()The reserve() function requests that the vector capacity be at least enough to contain n elements. Syntaxvoid reserve(size_type new_cap); How std::vector::reserve() works?The std::vector::reserve() does not change the size of the vector but ensures that the vector can grow to the reserved capacity without further reallocations.
When should we use std::vector::reserve()?You should reserve capacity in advance with reserve() if you know you will insert a large number of new elements into the vector. By reservation of capacity in advance, you avoid multiple reallocations, which, in terms of performance, can be very expensive. Example
Output Size of vector after reserve(10): 0 Capacity of vector after reserve(10): 10 Elements of vector after reserve(10): Time complexity: O(n), where n is the new capacity allocated. Difference between std::vector::resize() and std::vector::reserve() in C++The below table lists the major differences between the vector resize() and vector reserve function in C++:
|
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 19 |