0 day streak
cpp / intermediate
Snippet

Pre-emptive Memory Allocation for Vectors

By using .reserve(), you manually set the capacity of a vector. This is a crucial performance optimization when you know the approximate number of elements beforehand, as it prevents expensive reallocations and data copying during growth.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>
#include <iostream>
void fillVector() {
std::vector<int> values;
values.reserve(1000); // Allocate memory upfront
for (int i = 0; i < 1000; ++i) {
values.push_back(i); // No reallocations occur here
}
std::cout << "Capacity: " << values.capacity() << std::endl;
}
Breakdown
1
values.reserve(1000);
Allocates memory for 1000 integers without changing the size (number of actual elements) of the vector.
2
values.push_back(i);
Adds elements efficiently because the space is already guaranteed to exist.