C++ Vector Capacity and Size

Introduction

The capacity of a vector is the number elements that it can store without allocating more memory.

The size of a vector is the number of elements it actually contains.

You can obtain the size and capacity of a vector by calling the size() or capacity() function.

These values are returned as integers of an unsigned integral type that is defined by your implementation. For example:

#include <iostream>
#include <iomanip>
#include <vector>
using std::vector;

int main()/*from   w  w  w  .  j  a va  2s. c  o  m*/
{

    std::vector<unsigned int> primes { 2u, 3u, 5u, 7u, 11u, 13u, 17u, 19u};
    std::cout << "The size is " << primes.size() << std::endl;
    std::cout << "The capacity is " << primes.capacity() << std::endl;
}
You can assign the size of the vector to an auto variable, for example:

auto nElements = primes.size();        // Store the number of elements



PreviousNext

Related