#include#include using namespace std; int main() { vector vec1; cout << "Initial capacity of vec1: " << vec1.capacity() << endl; vec1.reserve(10); cout << "Capacity of vec1 after reserving space: " << vec1.capacity() << endl; for (int i=0; i<5; i++) { vec1.push_back(i*2); } cout << "Capacity of vec1 after adding 5 elements: " << vec1.capacity() << endl; vec1.erase(vec1.begin(), vec1.end()); // remove all elements cout << "Capacity of vec1 after erasing all elements: " << vec1.capacity() << endl; return 0; }
#includeThis example demonstrates the use of resize() and shrink_to_fit() functions in a vector. It creates a vector of doubles, vec2, with 5 elements of value 3.14 and prints its initial capacity. Then, it resizes vec2 to contain 10 elements of value 5.2 and prints the new capacity. Next, it changes the values of the elements using [] operator and prints the same capacity after calling shrink_to_fit() function, which reduces the capacity to the minimum amount of memory required to store the current elements. Package/library: STL (Standard Template Library)#include using namespace std; int main() { vector vec2(5, 3.14); cout << "Initial capacity of vec2: " << vec2.capacity() << endl; vec2.resize(10, 5.2); cout << "Capacity of vec2 after resizing: " << vec2.capacity() << endl; for (int i=0; i<10; i++) { vec2[i] = i*1.5; } vec2.shrink_to_fit(); cout << "Capacity of vec2 after shrinking: " << vec2.capacity() << endl; return 0; }