-->

C++ - Vectors Part 4: Capacity and Size Operations

Vectors provide methods to manage and query their size and capacity.

Examples and Explanation

Checking Size and Capacity

std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << "\n";

Explanation: size() returns the number of elements, while capacity() indicates the allocated memory for potential elements.

Resizing a Vector

vec.resize(10); // Resize to hold 10 elements

Explanation: The resize() method adjusts the size of the vector. If the new size is larger, additional elements are initialized to default values.

Checking Empty Vectors

if (vec.empty()) {

    std::cout << "Vector is empty.";

}

Explanation: The empty() method checks if a vector contains elements.

Shrinking to Fit

vec.shrink_to_fit();

Explanation: Reduces the capacity of a vector to match its size, releasing unused memory.