How do I reserve capacity and shrink-to-fit with std::vector?

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.

Example of Reserving Capacity and Shrinking to Fit

#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; }

C++ std::vector reserve shrink_to_fit memory management performance optimization