Open In App

How to Find the Size of a Vector in C++?

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

Output
4

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 Iterators

The 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;
}

Output
4

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.

Note: We can also use distance() method instead of directly subtracting the iterators.

By Counting

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;
}

Output
4

Next Article
Article Tags :
Practice Tags :

Similar Reads