Open In App

Vector size() in C++ STL

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

In C++, the vector size() is a built-in method used to find the size of a vector. The size of a vector tells us the number of elements currently present in the vector. In this article, we will learn about the vector size() method.

Let's take a look at the simple code example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 5, 4};

    // Finding the size of v
    cout << v.size();

    return 0;
}

Output
5

Explanation: The number of elements in the vector v is 5, which is returned by the vector size() function.

Syntax of Vector size()

The vector size() method is the member function of std::vector defined inside <vector> header file.

v.size();

This function does not take any parameters.

Return Value

  • Returns the number of elements in the vector as size_t value.
  • If the vector is empty, returns 0.

Example of Vector size()

The vector size() is a very simple and easy to use function. The code examples below show how to use this function:

Find the Number of Elements in Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2};

    // Finding the size of v
    cout << v.size() << endl;

    v.insert(v.end(),{3, 5, 4});

    // Finding the size of v
    cout << v.size();

    return 0;
}

Output
2
5

Check if Vector is Empty

The size() method can be used to check whether a vector is empty by comparing its size to zero.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

  	// Check if vector is empty
    if (v.size() == 0)
        cout << "Empty.";
    else
        cout << "Not empty.";

    return 0;
}

Output
Empty.

Traverse the Vector Using Index and size()

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 5, 4};

    // Print elements using a loop
    for (size_t i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }

    return 0;
}

Output
1 2 3 5 4 

Vector size() vs capacity()

The vector size() returns the number of elements currently stored in the vector while vector capacity() returns the total number of elements the vector can hold before needing to reallocate memory.

Featuresize()capacity()
PurposeReturns the number of elements in the vector.Returns the total memory capacity allocated to the vector.
Dynamic BehaviourIncreases when elements are added. Decreases when the element is deleted.May remain the same until a reallocation occurs.
RelationThe vector size is always less than or equal to the vector capacity.Vector capacity is always greater than or equal to the vector size.

Next Article
Practice Tags :

Similar Reads