In this C++ tutorial, you will learn how to get the size or length of a vector using vector::size() function, with examples.
C++ Vector Size
To get the size of a C++ Vector, you can use size() function on the vector.
size() function returns the number of elements in the vector.
Examples
1. Find Vector Length using size()
In the following C++ program, we define a vector of integers, add some elements to it, and then find its length using size() function.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push_back(24);
nums.push_back(81);
nums.push_back(57);
cout << nums.size();
}
Output
3
2. Length of Empty Vector
In the following C++ program, we define a vector of integers, with no elements in it, and then find its length using size() function. size() should return a value of zero.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
cout << nums.size();
}
Output
0
3. Length of Vector using Foreach
You can also use C++ Foreach statement to get the length of size of a vector.
In the following program, we shall define a vector and initialize with elements. Then take a len variable with zero initial value that acts as a counter to count the number of elements in the vector. Use Foreach statement to iterate over the elements of vector and increment the counter during each iteration.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push_back(24);
nums.push_back(81);
nums.push_back(57);
int len = 0;
for (int element: nums)
len++;
cout << len;
}
Output
3
Conclusion
In this C++ Tutorial, we learned to find the size of vector, which is the number of elements in a vector using builtin functions or statements like foreach.