Iterator

An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range. 

Syntax

type_container :: iterator var_name;

Example

The below example demonstrates the use of iterators.

C++




// C++ program to demonstrate iterators
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    // Declaring a vector
    vector<int> v = { 1, 2, 3 };
  
    // Declaring an iterator
    vector<int>::iterator i;
  
    int j;
  
    cout << "Without iterators = ";
  
    // Accessing the elements without using iterators
    for (j = 0; j < 3; ++j) {
        cout << v[j] << " ";
    }
  
    cout << "\nWith iterators = ";
  
    // Accessing the elements using iterators
    for (i = v.begin(); i != v.end(); ++i) {
        cout << *i << " ";
    }
  
    // Adding one more element to vector
    v.push_back(4);
  
    cout << "\nWithout iterators = ";
  
    // Accessing the elements without using iterators
    for (j = 0; j < 4; ++j) {
        cout << v[j] << " ";
    }
  
    cout << "\nWith iterators = ";
  
    // Accessing the elements using iterators
    for (i = v.begin(); i != v.end(); ++i) {
        cout << *i << " ";
    }
  
    return 0;
}


Output

Without iterators = 1 2 3 
With iterators = 1 2 3 
Without iterators = 1 2 3 4 
With iterators = 1 2 3 4 

Difference between Iterators and Pointers in C++ with Examples

In C++ programming, we have both pointers and iterators that are used in managing and manipulating data structures. There are many similarities between iterators and pointers in their ability to reference and dereference memory, but there are certain differences between the two. Understanding the difference is very important in C++ programming.

Similar Reads

Pointer

A pointer is a variable that contains the address of another variable, i.e., the address of the memory location of the variable. Like any variable or constant, we must declare a pointer before using it to store any variable address....

Iterator

...

Difference between Iterators and Pointers

An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range....