×

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage.

Because vector items are stored in contiguous storage, iterators can access and traverse them.

Data is appended to vectors at the end. Inserting at the end takes longer because the array may need to be enlarged often.

The final data element cannot be removed because no resizing is involved. When a data element is added or deleted at the start or the halfway point, time is linear.

A vector is a container that sequentially stores elements rather than using an index. Because a vector is dynamic, the size grows as elements are added.

Vector uses more memory. Accessing items in Vector takes longer.

The vector is realized as a dynamic array with an interface. The interface used is the list interface.

Length of C++ vector

Use the size() method on a C++ vector to determine its size or length.

The size() function returns the vector's element count. The element count is referred to as the length of the vector.

Example 1

Finding the vector length using the size() method in C++. In the C++ program below, a vector of integers is created, adding some data members to the vector. After adding the data elements, the size() method determines the vector's length or the vector size.

The following program code will display the length of the vector named count.

#include <iostream>
#include <vector>
using namespace std ;
 
int main() {
   vector<int> count ;
   count.push_back(2) ;
   count.push_back(8) ;
   count.push_back(5) ;
   count.push_back(10) ;
   count.push_back(54) ;
   count.push_back(100) ;
   count.push_back(99) ;
   cout << "The length of the vector is: " ;
   cout << count.size() ;
}

Output

How to find the length of the vector in C++

Example 2

Size of the vector that is empty.

In the C++ program below,  An empty vector is created. The empty vector is of integers. After defining the vector,   the size() method is used to determine the length or size of the vector. 

The result of size() should be 0.

#include <iostream>
#include <vector>
using namespace std ;
 
int main() {
   vector<int> vec ; // vec is the vector variable
   cout << "The vector size is " ;// Using size() method to display 
                                  //the length of the vector
   cout << vec.size() ;
}
How to find the length of the vector in C++

Example 3

Determining the size of the vector using the foreach loop.

C++ foreach loop helps in finding the length or size of the vector. First, define the vector, give it a name, and initialize it with elements. The below program initializes the vector and uses the foreach loop. Then, using the “l” variable with a zero initial value, count the number of elements in the vector. Next, using the “l” variable with a zero initial value, count the number of elements in the vector.

To iterate over the elements of the vector and increment the counter during each iteration, use the foreach loop.

#include <iostream>
#include <vector>
using namespace std ;
 
int main() {
   vector<int> vec; //variable "vec" is the vector variable
   vec.push_back(7) ;
   vec.push_back(18) ;
   vec.push_back(45) ;
   vec.push_back(333) ;
   vec.push_back(17) ;
 
   int l = 0 ;  //Using the variable "l" to display the length
   for (int element: vec)
      l++ ; 
   cout << "The length of the vector is " ;
   cout << l ; //prints the length of the vector
}
How to find the length of the vector in C++

Example 4

Displaying the length of the vector. The user gives the vector elements as user input.

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


//main function
int main() {
    int input ; 
    cin>>input; // taking the size of the vector as the user input
    int a ;
    vector<int> vec;
    // the size of the vector can also be mentioned here.
    // Another way to mention the size of the vector is vector<int> v(input);
    for(int i=0 ; i<input ; i++)
    {
        cin>>a ;
        vec.push_back(a);
    }
    for(auto &p : vec)
    {
        cout<<p<<" " ;
    }
    cout << "\nThe given length of the vector is " ;
    cout << vec.size() ;
    cout<<endl ;
    return 0 ;
}

Output 1

How to find the length of the vector in C++

Output 2

How to find the length of the vector in C++

Related Topics

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.