Iterators in STL

Ayushi Sheode
2 min readJan 7, 2021
Photo by Lauren Mancke on Unsplash

Introduction :

What are iterators?

• Iterators act like pointers and are used to access elements of the container.

• We use iterators to move through the contents of containers.

• Iterators are handled just like pointers.

• We can increment or decrement them as per our requirements.

• Iterators connect containers with algorithms and play a vital role in the manipulation of data

stored in the containers.

• They are often used to pass through from one element to another, this process is called iterating

through the container.

• There are five types of iterators:

➢ Input

➢ Output

➢ Forward

➢ Bidirectional

➢ Random

• Different types of iterators must be used with the different types of containers such

that only sequence and associative containers are allowed to travel through

iterators.

• Each type of iterators is used for performing certain functions.

• The input and output iterators support the least functions.

• They can be used only to pass through in a container.

• The forward iterators support all operations of input and output iterators and also

retain its position in the container.

• A Bidirectional iterator, while supporting all forward iterators operations, provides

the ability to move in the backward direction in the container.

Iterator implementation in Vectors :

#include <iostream>

#include <vector>

using namespace std;

int main() {

vector<int> vec;

int i;

for(i = 0; i < 5; i++) {

vec.push_back(i);

}

// access 5 values from the vector

for(i = 0; i < 5; i++) {

cout << “value of vec [“ << i << “] = “ << vec[i] << endl;

}

// use iterator to access the values

vector<int>::iterator v = vec.begin();

while( v != vec.end()) {

cout << “value of v = “ << *v << endl;

v++;

}

return 0;

}

Iterator implementation in Map:

/ Create a map and insert some values

std::map<char,int> mymap;

mymap[‘b’] = 100;

mymap[‘a’] = 200;

mymap[‘c’] = 300;

// Iterate over all tuples

for (std::map<char,int>::iterator it = mymap.begin(); it != mymap.end(); ++it)

std::cout << it->first << “ => “ << it->second << ‘\n’;

Iterator implementation in Multimap:

// multimap::begin/end

#include <iostream>

#include <map>

int main ()

{

std::multimap<char,int> mymultimap;

mymultimap.insert (std::pair<char,int>(‘a’,10));

mymultimap.insert (std::pair<char,int>(‘b’,20));

mymultimap.insert (std::pair<char,int>(‘b’,150));

// show content:

for (std::multimap<char,int>::iterator it=mymultimap.begin(); it!=mymultimap.end(); ++it)

std::cout << (*it).first << “ => “ << (*it).second << ‘\n’;

return 0;

}

These are a few examples of the implementation of iterators.

Thanks for reading !!!

--

--