Horje
std::vector::resize() vs. std::vector::reserve()

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.

Prerequisite

Before discussing the main topic, we first need to know the difference between the vector size and vector capacity.

  • Size: The number of items currently in the vector.
  • Capacity: The number of allocated memory spaces for the vector that can be greater or equal to the size.

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.

Syntax

void 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.

  • If the new size is larger than the current size, then it appends additional elements, which are default-initialized or initialized with the value.
  • If the new size is smaller, then the extra elements are simply removed.

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

C++
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Creating an empty vector of integers
    vector<int> vec;

    // Resize the vector to contain 5 elements
    vec.resize(5);

    // Output the size and elements of the vector
    cout << "Size of vector after resize(5): " << vec.size()
         << endl;
    cout << "Elements of vector after resize(5): ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl << endl;

    // Resize the vector to contain 3 elements with a
    // specific value (100)
    vec.resize(3, 100);

    // Output the size and elements of the vector
    cout << "Size of vector after resize(3, 100): "
         << vec.size() << endl;
    cout << "Elements of vector after resize(3, 100): ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

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.

Syntax

void 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.

  • If new_cap is greater than the current capacity, it increases the capacity to n.
  • If new_cap is less than or equal to the current capacity, it does nothing.

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

C++
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Creating an empty vector of integers
    vector<int> vec;

    // Reserve capacity for at least 10 elements
    vec.reserve(10);

    // Output the size, capacity, and elements of the vector
    cout << "Size of vector after reserve(10): "
         << vec.size() << endl;
    cout << "Capacity of vector after reserve(10): "
         << vec.capacity() << endl;
    cout << "Elements of vector after reserve(10): ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

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++:

Aspectresize()reserve()
PurposeChanges the number of elements in the vectorChanges the capacity of the vector.
Impact on SizeModifies the size.Does not modify the size.
Impact on CapacityMay modify the capacity.Modifies the capacity if needed.
Element InitializationAdds default-initialized or specific elements.Does not initialize any elements.
UsageAdjust the vector to a specific size.Optimize memory allocation for future growth.
Syntaxvoid resize(size_type count);
void resize(size_type count, const T& value);
void reserve(size_type n);
When to UseWhen you need a vector of a specific size with initialized elementsWhen you want to pre-allocate memory for a known or estimated future size to avoid reallocations
Performance ConsiderationsMay cause reallocation and copying of elements if increasing size beyond current capacity.Minimizes the number of reallocations by setting a sufficient capacity beforehand.
Effect on Existing ElementsTruncates or expands the vector, potentially adding new elements.No effect on existing elements.



Reffered: https://www.geeksforgeeks.org


C++

Related
UTF-8 to Wide Char Conversion in C++ STL UTF-8 to Wide Char Conversion in C++ STL
How to Convert wstring to string in C++? How to Convert wstring to string in C++?
How to Erase Duplicates and Sort a Vector in C++? How to Erase Duplicates and Sort a Vector in C++?
How to Get std::vector Pointer to Raw Data in C++? How to Get std::vector Pointer to Raw Data in C++?
Difference Between STL and Standard Library in C++ Difference Between STL and Standard Library in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19