The Capacity and Size of a Vector - C++ STL

C++ examples for STL:vector

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:

Demo Code

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

int main()/*from www  .ja v a  2  s.  com*/
{

    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;
}

Result

You can assign the size of the vector to an auto variable, for example:

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

Related Tutorials