Resizing a C++ Vector Without Initializing New Elements
To resize a vector without initializing new elements, we can use the std::vector::reserve function provided by the STL that changes the capacity of the vector, but not its size. So, by using std::reserve
, we can avoid unnecessary reallocations by allocating enough memory upfront and avoiding the initialization of the new elements.
C++ Program to Resize a Vector Without Initializing New Elements
The below example demonstrates how we can resize a vector without initializing new elements in C++.
// C++ Program to resize a vector without initializing new
// elements
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Intialize a vector
vector<int> vec = { 1, 2, 3, 4, 5 };
// Print the original vector
cout << "Original Vector:";
for (auto ele : vec) {
cout << ele << " ";
}
cout << endl;
// Print the original size and capacity of the vector
cout << "Original size: " << vec.size() << endl;
cout << "Original capacity: " << vec.capacity() << endl
<< endl;
// Resize the vector using reserve() function
int newSize = 10;
vec.reserve(newSize);
// Print the resized vector
cout << "Resized Vector:";
for (auto ele : vec) {
cout << ele << " ";
}
cout << endl;
// Print the size and capacity after calling reserve
cout << "Size after reserve: " << vec.size() << endl;
cout << "Capacity after reserve: " << vec.capacity()
<< endl;
return 0;
}
Output
Original Vector:1 2 3 4 5 Original size: 5 Original capacity: 5 Resized Vector:1 2 3 4 5 Size after reserve: 5 Capacity after reserve: 10
Time Complexity: O(N) where N is the size of the resized vector.
Auxiliary Space: O(N)
avoiding
How to Resize a Vector Without Initializing New Elements in C++?
In C++, vectors are dynamic arrays because they can change their size dynamically during the insertion and deletion of elements. In this article, we will learn how to resize a vector without initializing new elements in C++.
Example
Input:
Vec ={1,2,3,4,5} , capacity=5
Output:
// Resized vector
Vec ={1,2,3,4,5}, capacity=10
Contact Us