An iterator is an object that behaves like a pointer to traverse and access elements of a container.
- They allow container traversal without exposing internal structure.
- Support container-independent algorithms like sort(), count(), and find().
- Types include Input, Output, Forward, Bidirectional, and Random Access.
- They are declared as container_type::iterator it; or auto it = container.begin();.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {10, 20, 30, 40};
// Using iterator to traverse the vector
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
return 0;
}
Output
10 20 30 40
Container Iterator Functions
- STL containers provide member functions that return iterators.
- These iterators usually point to the first and last elements of the container.
- Most STL containers support these functions; exceptions include containers with limited access like stack and queue.
- The functions have consistent names across containers for uniformity.
List of all methods that returns the iterator to the containers:
- begin(): Returns an iterator to the beginning of container.
- end(): Returns an iterator to the theoretical element just after the last element of the container.
- cbegin(): Returns a constant iterator to the beginning of container. A constant iterator cannot modify the value of the element it is pointing to.
- cend(): Returns a constant iterator to the theoretical element just after the last element of the container.
- rbegin(): Returns a reverse iterator to the beginning of container.
- rend(): Returns a reverse iterator to the theoretical element just after the last element of the container.
- crbegin(): Returns a constant reverse iterator to the beginning of container.
- crend(): Returns a constant reverse iterator to the theoretical element just after the last element of the container.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = {10, 20, 30, 40, 50};
// Normal iterator
cout << "Forward iteration: ";
for (auto it = vec.begin(); it != vec.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
// Constant iterator
cout << "Forward (read-only) iteration: ";
for (auto it =