C++ vector capacity() Function
Example
Compare the size and the capacity of a vector:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.reserve(10);
cout << "Size: " << cars.size() << "\n";
cout << "Room for 10 cars: " << (cars.capacity() >= 10 ? "Yes" : "No");
Definition and Usage
The capacity() function returns how many elements the vector has room for, in the memory it has reserved.
The capacity is always the same as, or larger than, the size (the number of elements). When there is no more room, the vector reserves more memory by itself.
The capacity function is defined in the <vector> header file.
Note: The exact capacity depends on the compiler, so the example only checks that there is room for at least 10 elements.
Syntax
vector.capacity();
Parameter Values
None.
Technical Details
| Returns: | The number of elements that the reserved memory can store, as a size_t (a non-negative integer). |
|---|
Related Pages
Read more about vectors in our Vector Tutorial.