An iterator is used to move through the elements of a C++ Standard Library container (vector, set, map etc.). It is analogous to array indexes or pointers. This pointer-like object that can be incremented or decremented, de-referenced (using *), and compared against another iterator. Vector iterators are random-access iterators, meaning, they can be used to access elements at any offset position relative to the element they point to.
There are 4 kinds of iterators that can be used with vectors:
1. vector::begin()
: Returns an iterator pointing to the first element in the vector.
2. vector::end()
: Returns an iterator pointing to an imaginary element after the last element in the vector.
3. vector::rbegin()
: Returns a reverse iterator pointing to the last element in the vector
4. vector::rend()
: Returns a reverse iterator pointing to an imaginary element before the first element
Syntax to create vector iterator:
vector<data_type>::iterator name; //standard iterator vector<data_type>::reverse_iterator name; //reverse iterator
Examples of iterators
Iterating in the forward direction
Note: ++
moves the iterator towards the right--
moves the iterator towards the left
#include <iostream> #include<vector> using namespace std; int main () { vector<char> vec; vec.push_back('A'); vec.push_back('B'); vec.push_back('C'); vec.push_back('D'); vec.push_back('E'); cout<<"The elements are: \n"; for (vector<char>::iterator it = vec.begin() ; it != vec.end(); ++it) cout<<*it<<" "; return 0; }
Output:
The elements are: A B C D E
Iterating in the reverse direction
Note:++
moves the iterator towards the left--
moves the iterator towards the right
#include <iostream> #include <vector> using namespace std; int main () { vector<char> vec; vec.push_back('A'); vec.push_back('B'); vec.push_back('C'); vec.push_back('D'); vec.push_back('E'); cout<<"The elements are: \n"; for (vector<char>::reverse_iterator it = vec.rbegin() ; it != vec.rend(); ++it) cout<<*it<<" "; return 0; }
Output:
The elements are: E D C B A
Accessing elements and de-referencing using iterators
#include <iostream> #include <vector> using namespace std; int main () { vector<int> vec; for(int i=1;i<=5;i++) vec.push_back(i); vector<int>::iterator it=vec.begin(); cout<<"The element at index 2 is: "<<*(it+2)<<endl; // dereferencing and accessing element cout<<"\n"; cout<<"Before increment, iterator points to index "<<it - vec.begin()<<endl; cout<<"Value at index: "<<*it<<endl; it++; cout<<"After increment, iterator points to index "<<it - vec.begin()<<endl; cout<<"Value at index: "<<*it<<endl; }
Output:
The element at index 2 is: 3 Before increment, iterator points to index 0 Value at index: 1 Before increment, iterator points to index 1 Value at index: 2