public member function
<vector>

std::vector::capacity

size_type capacity() const;
size_type capacity() const noexcept;
Return size of allocated storage capacity
Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.

Notice that this capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size.

The capacity of a vector can be explicitly altered by calling member vector::reserve.

Parameters

none

Return Value

The size of the currently allocated storage capacity in the vector, measured in terms of the number elements it can hold.

Member type size_type is an unsigned integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// comparing size, capacity and max_size
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  std::cout << "size: " << (int) myvector.size() << '\n';
  std::cout << "capacity: " << (int) myvector.capacity() << '\n';
  std::cout << "max_size: " << (int) myvector.max_size() << '\n';
  return 0;
}


A possible output for this program could be:
size: 100
capacity: 128
max_size: 1073741823

Complexity

Constant.

Iterator validity

No changes.

Data races

The container is accessed.
No contained elements are accessed: concurrently accessing or modifying them is safe.

Exception safety

No-throw guarantee: this member function never throws exceptions.

See also

  • 997351548 2018-02-20
  • 903691547 2018-02-20
  • 9127171546 2018-02-20
  • 2234751545 2018-02-20
  • 1685381544 2018-02-20
  • 911091543 2018-02-20
  • 9281021542 2018-02-20
  • 632231541 2018-02-20
  • 9751491540 2018-02-20
  • 8333621539 2018-02-20
  • 995001538 2018-02-20
  • 6477441537 2018-02-20
  • 511981536 2018-02-19
  • 2072881535 2018-02-19
  • 6024461534 2018-02-19
  • 7594061533 2018-02-19
  • 9311341532 2018-02-19
  • 4928331531 2018-02-19
  • 38561530 2018-02-19
  • 7776611529 2018-02-19