In this article, we will learn how to iterate through the vector without using iterator in C++.
The most efficient method to iterate through the vector without using iterator is by using traditional for loop. It accesses all the elements using index starting from 0 to vector size() - 1. Let’s take a look at an example:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
// Iterating through vector
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
Output
1 4 6 7 9
Explanation: In the above code, we provide the index in the vector operator[] using traditional for loop to iterate through the vector.
There is also another method to iterate through vector without using iterator in C++.
Using Range Based for Loop
The range-based for loop is a simple and concise way to iterate over the elements of a vector without asking for any iterator or index. (though internally it uses iterators)
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
// Iterating through vector
for (auto i : v)
cout << i << " ";
return 0;
}
Output
1 4 6 7 9