How to Find the Number of Elements in a Vector Array in C++


C++


In this article, we show how to find the number of elements in a vector array in C++.

A vector array is like a regular array but is adaptable, in that new elements can be added or removed from the array.

So let's say we have a vector array created in our code with items in it. How can we then find the number of elements in the vector array? This is useful for many things such as if you're looping through all the elements in the array. To know where the for loop ends, you have to know how many elements are in the vector array.

To do this, we use the size() function. The size() function returns the number of elements in the vector array as an integer.

Below we created a vector array that has the elements, 1,4,7,9.

The code below finds the number of elements in the array using the size() function.



In order to create a vector array and work with vectors in C++, you must include the vector class.

We create a vector that has 4 elements: 1,4,7, and 9.

We then display the number of elements in the vector array by using the size() function. In this case, the size of the array is 4; the vector array has 4 elements.

Getting the size of the vector array is important because we then use this information in order to loop through all the elements of the vector array. Once we know the size of a vector array, we can know how many elements there are to loop through.

We create a for loop that then displays all of the elements in the vector array.

So this is how we can find the number of elements in a vector array in C++.


Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...