In C++, when working with `std::vector`, it's often important to manage memory efficiently. Reserving capacity using the `reserve()` method allows you to avoid multiple allocations as elements are added to the vector. This can significantly improve performance, especially in scenarios where the number of elements is known in advance. Conversely, when you want to reduce the memory usage of a vector after its capacity has exceeded the needed size, you can use the `shrink_to_fit()` method. This instructs the vector to reduce its capacity to fit its size, releasing any excess memory.
#include
#include
int main() {
std::vector vec;
// Reserve capacity for 10 elements
vec.reserve(10);
std::cout << "Capacity after reserve: " << vec.capacity() << std::endl;
// Add 10 elements
for (int i = 0; i < 10; i++) {
vec.push_back(i);
}
std::cout << "Capacity after adding 10 elements: " << vec.capacity() << std::endl;
// Shrink to fit
vec.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit: " << vec.capacity() << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?