Namespaces
Variants
Views
Actions

std::vector<T,Allocator>::capacity

From cppreference.com
< cpp‎ | container‎ | vector
 
 
 
 
size_type capacity() const;
(until C++11)
size_type capacity() const noexcept;
(since C++11)
(until C++20)
constexpr size_type capacity() const noexcept;
(since C++20)

Returns the number of elements that the container has currently allocated space for.

Contents

[edit] Parameters

(none)

[edit] Return value

Capacity of the currently allocated storage.

[edit] Complexity

Constant.

[edit] Example

#include <iostream>
#include <vector>
 
int main()
{
    int sz = 200;
    std::vector<int> v1;
 
    auto cap = v1.capacity();
    std::cout << "initial capacity=" << cap << '\n';
 
    for (int n = 0; n < sz; ++n) {
        v1.push_back(n);
        if (cap != v1.capacity()) {
            cap = v1.capacity();
            std::cout << "new capacity=" << cap << '\n';
        }
    }
 
    std::cout << "final size=" << v1.size() << '\n';
    std::cout << "final capacity=" << v1.capacity() << '\n';
}

Possible output:

initial capacity=0
new capacity=1
new capacity=2
new capacity=4
new capacity=8
new capacity=16
new capacity=32
new capacity=64
new capacity=128
new capacity=256
final size=200
final capacity=256

[edit] See also

returns the number of elements
(public member function) [edit]
reserves storage
(public member function) [edit]