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

In C++, vectors in C++ are dynamic arrays that can grow or shrink in size as elements are added or removed. In this article, we will learn how to find the size of a vector in C++.

Example

Input: myVector = {1, 2, 3, 4, 5, 6, 7, 8}

Output : Size of the vector: 8

Find the Size of the Vector in C++

In C++, the vector contains keep track of their size themselves. We can simply use the std::vector::size() member function of the std::vector class to get the size of the vector container. It returns the size i.e. number of elements present in the vector in the form of an integer.

C++ Program to Find the Size of the Vector

C++

// C++ Program to Print Size of a Vector
  
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Print the elements of the vector
    cout << "Vector: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
  
    // Find the size of the vector
    cout << "Size of the Vector: " << vec.size() << endl;
  
    return 0;
}

Output

Vector: 1 2 3 4 5 6 7 8 
Size of the Vector: 8

Time complexity: O(1)
Auxilary space : O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find a Pair by Key in a Vector of Pairs in C++? How to Find a Pair by Key in a Vector of Pairs in C++?
How to Compare Two Pairs in C++? How to Compare Two Pairs in C++?
How to Find the Size of an Array Using Pointer to its First Element? How to Find the Size of an Array Using Pointer to its First Element?
How to Read a File Using ifstream in C++? How to Read a File Using ifstream in C++?
Mode of Elements in Sorted Vector in C++ Mode of Elements in Sorted Vector in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14