Navigate through a vector using iterators in C++

Hello readers! In this tutorial, we are going to learn and implement how to navigate through a vector using iterators in C++.

Before we proceed further let’s have a look at what are iterators and their syntax.

What are iterators?

Iterators in vectors are random-access iterators and they look like plain pointers.

They can access any element and also iterators can access/navigate the whole vector till the last nth element in that particular vector.

Using iterators we can reduce our code complexity and can do our task far easier.

Syntax:

<container_type>::iterator

container type: This is a parameter used to declare the type of container required on which the iterator needs to work.

Let’s see an example through a code.

C++ Code: Navigate a vector using iterators

Read the comments in the code for better understanding.

#include<iostream>
#include<vector>
#include<iterator>
using namespace std;
int main(){
vector<int>v; //initialise name of vector
v.push_back(100); // insert 4 elements inside the vector v.
v.push_back(200);
v.push_back(300);
v.push_back(400);
vector<int>::iterator it1=v.begin(); // using iterator it1 in container vector.
while(it1 !=v.end()){            // using while loop to navigate vector till end 
    cout<<*it1<<endl;
    it1++;
}
}

Output:

100
200
300
400

Explanation to the above code

First, we will give the name of the vector as v. Then using push_back() we will insert 4 elements in the vector v.  We will use iterator it1 put the value of the container as vector<int> then the iterator it1  will start navigating from the beginning as v.begin() function is declared. Use the while loop and v.end() function to navigate the vector till the end.  All the elements inserted  in the vector will be printed as output

That’s it for this tutorial.

Thank You!

Leave a Reply

Your email address will not be published.