Prerequisite: C++ STL, Iterators in C++ STL
The iterator is not the only way to iterate through any STL container. There exists a better and efficient way to iterate through vector without using iterators. It can be iterated using the values stored in any container. Below is the syntax for the same for vectors:
Syntax:
for(auto itr : vector_name)
Explanation: Here itr is the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > arr = { 1, 2, 3, 4 };
for ( auto & it : arr) {
cout << it << ' ' ;
}
return 0;
}
|
Updating values in vector: For updating values in a vector without using iterators traverse the values stored in vector using reference and updated the value. Below is the syntax for the same:
Syntax:
for(auto &itr : vector_name)
Explanation: Here itr is an address to the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same:
#include <bits/stdc++.h>
using namespace std;
void updateVector(vector< int > arr)
{
cout << "Vector Before Update: " ;
for ( auto & it : arr) {
cout << it << ' ' ;
}
for ( auto & it : arr) {
it *= 2;
}
cout << "\nVector After Update: " ;
for ( auto & it : arr) {
cout << it << ' ' ;
}
}
int main()
{
vector< int > arr = { 1, 2, 3, 4 };
updateVector(arr);
return 0;
}
|
Output:
Vector Before Update: 1 2 3 4
Vector After Update: 2 4 6 8
Advantages:
- Simple and easy to write code.
- Better and efficient than using iterators method.
Disadvantages:
- It iterates only in forward direction.
- Keeps no counter i.e., We cannot find the index of any element with this traversal. For counting the element, the counter have to taken explicitly.
We can also iterate using the same traversal in many different Containers in C++. Below are the illustration for the same:
- Map:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > Mp;
Mp[1] = 1;
Mp[2] = 2;
Mp[3] = 3;
for ( auto it : Mp) {
cout << it.first << ' '
<< it.second << endl;
}
return 0;
}
|
- Map of Vectors:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , vector< int > > Mp;
vector< int > temp = { 1, 2, 3 };
Mp[1] = temp;
temp = { 2, 3, 8, 9 };
Mp[2] = temp;
temp = { 10, -2 };
Mp[3] = temp;
for ( auto it : Mp) {
cout << it.first << " -> " ;
for ( auto jt : it.second) {
cout << jt << ' ' ;
}
cout << endl;
}
return 0;
}
|
Output:
1 -> 1 2 3
2 -> 2 3 8 9
3 -> 10 -2
- Set:
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > S;
S.insert(3);
S.insert(-1);
S.insert(3);
S.insert(4);
for ( auto it : S) {
cout << it << ' ' ;
}
return 0;
}
|
- Deque:
#include <bits/stdc++.h>
using namespace std;
int main()
{
deque< int > dq;
dq.push_front(1);
dq.push_front(2);
dq.push_front(3);
dq.push_back(4);
dq.push_back(5);
for ( auto it : dq) {
cout << it << ' ' ;
}
return 0;
}
|