Last Updated : 23 Jul, 2025
The size of a vector means the number of elements currently stored in the vector container. In this article, we will learn how to find the size of vector in C++.
The easiest way to find the size of vector is by using vector size() function. Let’s take a look at a simple example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 7, 9};
// Finding the size of vector
cout << v.size();
return 0;
}
Explanation: The vector container automatically tracks its own size which can be efficiently retrieved by size() method.
There are also some other methods in C++ to find the size of vector. They are as follows:
Using IteratorsThe vector store all its elements sequentially in a continuous memory. It means that all the elements between the memory address of first and last element belongs to that vector.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 7, 9};
// Find the size of vector
cout << v.end() - v.begin();
return 0;
}
Explanation: We find the number of elements in vector by subtracting the vector begin() iterator which points to the first element and vector end() iterator which point to the element just after the last element.
By CountingNote: We can also use distance() method instead of directly subtracting the iterators.
Range based for loop allows users to iterate an STL container without needing its size or iterator. We can use this property to determine the size of the vector by counting the number of iterations.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 7, 9};
// Initialize the counter with 0
int c = 0;
// Count number of elements in vector manually
for (auto i : v)
c++;
cout << c;
return 0;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4