How to iterate through vector in C++
In this section, we will see how can we iterate through the elements of the vector. There are three ways to iterate through vector elements. In this tutorial, we will learn these three methods.
The Vector in C++ is a dynamic array that can automatically grow and reduce its size when the elements get added or removed respectively. Like an array, elements of vectors are at the contiguous memory locations. This property helps us in random access of the elements easily using the index and also to iterate over its element to do any kind of operations. It has a great advantage over the array.
Iterate through C++ vectors using range based for loop
It is introduced in C++11 and it is mostly used because it makes the code more readable. We will understand this using an example in which we will traverse through the vector and output the elements in sequential form.
#include <bits/stdc++.h> using namespace std; // main function int main() { // declaration of vector vector<int> v{10, 9, 30, 40}; /* traverse through the range based for loop and display its elements */ for (auto& a : v) { cout << a << " "; } return 0; }
Output:
10 9 30 40
In the above code, we have used auto keyword to iterate over the vector elements. This will automatically determine the type of elements in the vector. It takes each element and provides it for the operations we want to do using it.
Iterate through C++ vectors using indexing
this method, there is a pre-requisite of some of the things like the length of the vector. This is the most common method we are using to iterate over the vector. We will understand this more using an example.
#include <bits/stdc++.h> using namespace std; //main function int main() { // decleration of vector vector<int> v{10, 35, 20, 13, 27}; // traverse through the vector using indexing for(int i = 0; i < v.size(); i++) { cout<<v[i]<<" "; } return 0; }
Output:
10 35 20 13 27
Iterate through C++ vectors using iterators
In C++, vector class provides us two functions using which we can get the start and end iterator of the vector. These two functions are begin(), end(). begin() function is used to get the pointer pointing to the start of the vector and end() functions is used to get the pointer pointing to the end of the vector.
Using this we can iterate over the vector and display the value using the output function. We will understand this using example.
#include<bits/stdc++.h> using namespace std; //main function int main() { // declaring a vector vector<int> v{11, 23, 26, 30, 24}; // declaring iterator of vector vector<int>::iterator it; // iterate over vector using iteration for(it = v.begin(); it != v.end(); it++) { cout<<*it<<" "; } return 0; }
Output:
11 23 26 30 24
Leave a Reply