C++ Iterate Over Vector – 4 Ways

Vector comes under STL. It can be termed as a dynamic array i.e, we can add or remove elements in vectors even in runtime. This flexibility with values is not possible in the arrays.

Vectors aren’t ordered in increasing or decreasing order, although they can be easily accessed by iterators.

There are different ways through which we can traverse through a vector. In this blog, we will be exploring all those ways.

1. Using for Loop

We will iterate through the vector by accessing all the indexes one after another inside the for loop.

Let us see the code for a better overview.

Output:

2. Using while Loop with at() Method

We will iterate through the vector by accessing all the indexes one after another using the at method inside while loop. Let us see the code for a better overview.

Output:

3. Using an Iterator

An iterator is declared which points to the beginning of the vector, and we increase the iterator by 1 till it doesn’t reach the end of the vector. Let us see the code for a better overview.

Output:

4. Using auto Keyword with for Loop

The auto keyword adjusts the datatype according to the needs. It can only be used with the for loop. Let us see the code for a better overview.

Output:

There are some similar ways in which we can use while, do-while loop but the main logic is the same. So I hope you have understood this blog clearly, feel free to comment below if you still have any doubts.

Leave a Comment

Your email address will not be published. Required fields are marked *