×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

vector::capacity() function with example in C++ STL

C++ STL vector::capacity() function: Here, we are going to learn about the capacity() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 13, 2019

C++ vector::capacity() function

vector::capacity() is a library function of "vector" header, it is used to find the capacity of a vector, it returns the storage space currently allocated to the vector.

Note: To use vector, include <vector> header.

Syntax

Syntax of vector::capacity() function

vector::capacity();

Parameter(s)

void – It accepts nothing as a parameter.

Return value

size_type – It returns capacity i.e. storage space of a vector.

Sample Input and Output

Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };

Function call:
cout << vector1.capacity();

Output:
8

C++ program to demonstrate example of vector::capacity() function

//C++ STL program to demonstrate example of
//vector::capacity() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v1;

    //printing the size & capacity of the vector
    cout << "Total number of elements: " << v1.size() << endl;
    cout << "Storage space: " << v1.capacity() << endl;

    //pushing elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the size & capacity of the vector
    cout << "Total number of elements: " << v1.size() << endl;
    cout << "Storage space: " << v1.capacity() << endl;

    return 0;
}

Output

Total number of elements: 0
Storage space: 0
Total number of elements: 5
Storage space: 8

Reference: C++ vector::capacity()

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.