Home »
C++ STL
vector::reserve() function with example in C++ STL
C++ STL vector::reserve() function: Here, we are going to learn about the reserve() function of vector header in C++ STL with example.
Submitted by Radib Kar, on May 17, 2019
C++ vector::reserve() function
vector::reserve() is a library function of "vector" header, which is used to request change in vector allocation. Refer to example to understand in details.
Note: To use vector, include <vector> header.
Syntax
Syntax of vector::reserve() function
vector::reserve(n);
Parameter(s)
int n – It accepts n as a parameter where n be the input capacity.
Return value
void – It returns nothing in case of valid request. But if the capacity requested is greater than the maximum size of the vector (vector::max_size), a length_error exception is thrown.
Sample Input and Output
Example: Case 1: (without reserve())
vector<int> arr1; //usual dynamic allocation
size = arr1.capacity();
cout << "arr1 growing with usual dynamic allocation:\n";
for (int i = 0; i < 50; ++i) {
arr1.push_back(i);
if (size != arr1.capacity()) {
size = arr1.capacity();
cout << "capacity changed to : " << size << '\n';
}
}
In this case, we have not used reserve thus the growth is as per dynamic allocation, which increases in a factor of two. Like, 1, 2, 4, 8, 16, 32, 64, 128…..so on till max_size.
Example: Case 2: (with reserve())
vector<int> arr2; //using reserve
size = arr2.capacity();
arr2.reserve(50); // use of reserve function
cout << "arr2 growing with using reverse:\n";
for (int i = 0; i < 50; ++i) {
arr2.push_back(i);
if (size != arr2.capacity()) {
size = arr2.capacity();
cout << "capacity changed to: " << size << '\n';
}
}
In this case, we have not used reserve thus the growth is as per dynamic allocation, which increases in a factor of two. Like, 1, 2, 4, 8, 16, 32, 64, 128…..so on till max_size.
C++ program to demonstrate example of vector::reserve() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>::size_type size;
vector<int> arr1; //usual dynamic allocation
size = arr1.capacity();
cout << "arr1 growing with usual dynamic allocation:\n";
for (int i = 0; i < 50; ++i) {
arr1.push_back(i);
if (size != arr1.capacity()) {
size = arr1.capacity();
cout << "capacity changed to : " << size << '\n';
}
}
vector<int> arr2; //using reserve
size = arr2.capacity();
arr2.reserve(50); // use of reserve function
cout << "arr2 growing with using reverse:\n";
for (int i = 0; i < 50; ++i) {
arr2.push_back(i);
if (size != arr2.capacity()) {
size = arr2.capacity();
cout << "capacity changed to: " << size << '\n';
}
}
return 0;
}
Output
arr1 growing with usual dynamic allocation:
capacity changed to : 1
capacity changed to : 2
capacity changed to : 4
capacity changed to : 8
capacity changed to : 16
capacity changed to : 32
capacity changed to : 64
arr2 growing with using reverse:
capacity changed to: 50
Reference: C++ vector::reserve()