Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
capacity
c++

What is the vector.capacity() function in C++?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The capacity() function is used to get the memory space that is currently allocated for the vector. This function is available in the <vector> header file.

Parameters

The capacity() function does not accept any parameters.

Return value

The capacity() function returns the size of the currently allocated storage capacity of the vector. This size is expressed in terms of the number of elements that the vector can hold.

Code

Now, let’s look at the code and see how the capacity() function is used:

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

int main() {
  vector<int> vec;
  cout << "The capacity of an empty vector: " << vec.capacity();
  
  vec.push_back(1);
  cout << "\nUpdated capacity of the vector: " << vec.capacity();

  vec.push_back(2);
  vec.push_back(3);
  cout << "\nUpdated capacity of the vector: " << vec.capacity();

  return 0;
}
Use vector.capacity() function in C++

Explanation

  • In lines 1 and 2, we import the required packages.

  • In line 6, we create an empty vector.

  • In line 7, we print the capacity of the empty vector, which comes out to be 0.

  • In lines 9 and 10, we insert an element to the vector and then print the capacity, which comes out to be 1.

  • In lines 12 to 14, we insert two elements to the vector and then print the capacity, which comes out to be 4. This happens because every time we run out of capacity, the vector doubles its capacity. Therefore, if we insert one element when the capacity of the vector is 1, the vector will double its size to 2. If we insert one more element, the vector will double its size to 4.

RELATED TAGS

communitycreator
capacity
c++

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring