# Difference between size and capacity of a vector in C++ STL

**C++ STL | size vs capacity of a vector**: Here, we are going to learn about the **difference between size and capacity of a vector**.

Submitted by **IncludeHelp**, on May 17, 2019

## 1) C++ STL vector size

The vector size is the total number of elements of a vector and it always the same for all compilers. To get the size of a vector, **vector::size() function** is used.

Read more: C++ STL vector::size() function

## 2) C++ STL vector capacity

Capacity is the memory space occupied by a vector; elements of a vector are stored as an array in the memory. Thus, the capacity is the amount of space which is currently using by the vector (or internal array). It will also equal to greater than the size of the vector. It may differ on the different compiler. To get the capacity of a vector, **vector::capacity() function** is used.

Read more: C++ STL vector::capacity() function

### C++ STL program to demonstrate difference between vector size and capacity

//C++ STL program to demonstrate difference between //vector size and capacity #include <iostream> #include <vector> using namespace std; int main() { //vector declaration vector<int> v1{ 10, 20, 30, 40, 50 }; vector<int> v2{ 100, 200, 300, 400 }; //size, capacity and elements of vector v1 cout << "size of v1: " << v1.size() << endl; cout << "capacity of v1: " << v1.capacity() << endl; cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; //size, capacity and elements of vector v2 cout << "size of v2: " << v2.size() << endl; cout << "capacity of v2: " << v2.capacity() << endl; cout << "v2: "; for (int x : v2) cout << x << " "; cout << endl; return 0; }

**Output**

size of v1: 5 capacity of v1: 5 v1: 10 20 30 40 50 size of v2: 4 capacity of v2: 4 v2: 100 200 300 400

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.