Table of contents
1.
Understanding
2.
Iterators in C++
3.
Types of Iterators
4.
Examples
4.1.
Program
4.2.
Output
5.
Functions on Iterators
5.1.
advance()
5.1.1.
Program
5.1.2.
Output
5.2.
distance()
5.2.1.
Program
5.2.2.
Output
5.3.
prev(), next() functions
5.3.1.
Program
5.3.2.
Output
6.
auto keyword
6.1.
Program
6.2.
Output
7.
Key Takeaways
Last Updated: Mar 27, 2024

Iterators & Auto Keyword

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Understanding

In this blog, we will discuss the concept of iterators in the C++ programming language. We will also overview the idea behind auto keyword in C++ and its various use cases. We will address various use cases of iterators in C++ STL containers.

Iterators are used to access the elements of many C++ STL containers like map, vector, set, etc. Similarly, auto keyword in C++ allows us to hold a value without knowing its data type, similar to python programming language.

Also see, Literals in C.Fibonacci Series in C++

Iterators in C++

Let us take an example to appreciate the concept of iterators in C++.

Let 'ARR' = {2, 1, 12, 7, 10, 12} be a vector in C++. We can access the elements of a vector by indexing. For example, we can access the first, third and fifth elements using 'ARR[0]', 'ARR[2]', 'ARR[4]', respectively. In general, we can access the ‘i’th element using 'ARR[i - 1]'.

 

Now let us consider a set in C++. Let us assume that the set consists of the following elements: 2, 4, 8, 9, 11. Can we access these elements using indexing as we did before? The answer is NO.

Apart from the set, there are many containers in C++ STL, for example, mapmultisetunordered_map, whose elements cannot be accessed using indexing.

Here comes the role of iterators. Iterators are pointer-like structures used to access and modify elements of C++ STL containers. Iterators point to memory locations that hold these elements, and they can be used to access or modify the value present in those locations.

Types of Iterators

Iterators can be grouped into five major categories based on their functionality:

Input Iterators: These are the most basic of all iterators, with minimal capability. They can only be utilised in single-pass algorithms, that is, algorithms that sequentially process the container so that no element is visited twice.

Output Iterators: They have very limited capability and can only be used in single-pass algorithms like input iterators. However, they can be assigned elements rather than accessing them.

Forward Iterator: These iterators are higher in the hierarchy than input and output iterators, and they have all of the same features. But, as the name implies, they can only go forward one step at a time.

Bidirectional Iterators: They have all of the benefits of forward iterators with the added benefit of going in both ways, which is why they are called bidirectional iterators.

Random-access iterators: The most powerful iterators are random-access iterators. They are not constrained to moving sequentially; as their name implies, they can access any element within the container at any time. They're the ones with the same functionality as pointers.

Examples

We can create iterators to iterate various C++ STL containers. Let us see an example to see how to create and advance iterators to point to different elements in a container.

Program

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <iterator>
using namespace std;


int main()
{
    // Create various C++ STL containers and iterate them.


    // Create a vector.
    vector<int> vec = {2, 8, 4, 5, 10};


    // Create an iterator to iterate the vector.
    vector<int>::iterator itVec;


    // begin() returns the pointer to the first element in the container.
    // end() returns the pointer to the memory location just after the last element in the container.
    // ++ operator is used to move to the next element in the container.


    cout << "Vector elements are: ";
    for (itVec = vec.begin(); itVec != vec.end(); itVec++)
    {
        cout << *itVec << " ";
    }
    cout << endl
         << endl;


    // Create a set and populate it with elements.
    set<int> st;
    st.insert(11);
    st.insert(9);
    st.insert(14);
    st.insert(1);


    cout << "Set elements are: ";


    // Create an iterator to iterate the set container.
    set<int>::iterator itSet;
    for (itSet = st.begin(); itSet != st.end(); itSet++)
    {
        cout << *itSet << " ";
    }
    cout << endl
         << endl;


    // Create a multiset and populate it with the following elements.
    multiset<int> mst;
    mst.insert(9);
    mst.insert(18);
    mst.insert(4);
    mst.insert(9);
    mst.insert(2);
    mst.insert(4);


    cout << "Multiset elements are: ";


    // Create an iterator to iterate the multiset container.
    multiset<int>::iterator itMultiset;


    // Iterate the multiset and print the elements.
    // Use begin() to get the pointer to the first element in the multiset.
    for (itMultiset = mst.begin(); itMultiset != mst.end(); itMultiset++)
    {
        cout << *itMultiset << " ";
    }
    cout << endl
         << endl;


    // Create a map container and populate it with some values.
    map<int, int> mapCpp;
    mapCpp[1] = 10;
    mapCpp[2] = 7;
    mapCpp[3] = 5;
    mapCpp[4] = 19;


    cout << "Map elements are: \n";


    // Create an iterator to iterate the map container.
    map<int, int>::iterator itMap;


    // Iterate the map container.
    for (itMap = mapCpp.begin(); itMap != mapCpp.end(); itMap++)
    {
        // An element in a map container is of the form of a pair.
        cout << itMap->first << " " << itMap->second;
        cout << endl;
    }
    cout << endl;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Vector elements are: 2 8 4 5 10 

Set elements are: 1 9 11 14 

Multiset elements are: 2 4 4 9 9 18 

Map elements are: 
1 10
2 7
3 5
4 19

 

Try and compile with online c++ compiler.

Functions on Iterators

advance()

This function is used to increment the iterator position till the specified number mentioned in its argument.

Program

#include <iostream>
#include <iterator>
#include <set>
using namespace std;


int main()
{
    // Create a set and populate it with elements.
    set<int> st;
    st.insert(11);
    st.insert(9);
    st.insert(14);
    st.insert(1);


    cout << "Set elements are: ";
    // Create an iterator to iterate the set container.
    set<int>::iterator itSet;
    for (itSet = st.begin(); itSet != st.end(); itSet++)
    {
        cout << *itSet << " ";
    }
    cout << endl
         << endl;


    set<int>::iterator ptr = st.begin();
    cout << "The position of iterator before advancing is : ";
    cout << *ptr << " ";
    cout << endl;



    // Advance the iterator by 2 positions.
    // itSet now points to 11.
    advance(ptr, 2);


    // Displaying iterator position
    cout << "The position of iterator after advancing is : ";
    cout << *ptr << " ";
    cout << endl
         << endl;


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Set elements are: 1 9 11 14 

The position of iterator after advancing is : 11

distance()

The distance() function returns the number of memory units between the locations pointed to by two pointers or iterators.

Program

#include <iostream>
#include <iterator>
#include <set>
using namespace std;


int main()
{
    // Create a set and populate it with elements.
    set<int> st;
    st.insert(11);
    st.insert(9);
    st.insert(14);
    st.insert(1);
    st.insert(7);
    st.insert(15);
    st.insert(12);


    cout << "Set elements are: ";


    // Create an iterator to iterate the set container.
    set<int>::iterator itSet;
    for (itSet = st.begin(); itSet != st.end(); itSet++)
    {
        cout << *itSet << " ";
    }
    cout << endl
         << endl;


    set<int>::iterator ptr1 = st.begin();


    // Advance the iterator by 2 positions.
    // ptr1 now points to 9.
    advance(ptr1, 2);


    set<int>::iterator ptr2 = st.begin();


    // Advance the iterator by 4 positions.
    // ptr2 now points to 12.
    advance(ptr2, 4);


    cout << "The distance between ptr1 and ptr2: ";
    cout << distance(ptr1, ptr2) << endl
         << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Set elements are: 1 7 9 11 12 14 15 
The distance between ptr1 and ptr2: 2

prev(), next() functions

The prev() and next() functions are used to get pointers to the prev and next elements in the container.

Program

#include <iostream>
#include <iterator>
#include <set>
using namespace std;


int main()
{
    // Create a set and populate it with elements.
    set<int> st;
    st.insert(11);
    st.insert(9);
    st.insert(14);
    st.insert(1);


    cout << "Set elements are: ";
    // Create an iterator to iterate the set container.
    set<int>::iterator itSet;
    for (itSet = st.begin(); itSet != st.end(); itSet++)
    {
        cout << *itSet << " ";
    }
    cout << endl
         << endl;


    set<int>::iterator ptr = st.begin();


    // Advance the iterator by 2 positions.
    // itSet now points to 11.
    advance(ptr, 2);


    // Current element pointed by ptr.
    cout << "The current element: " << *ptr << endl;


    set<int>::iterator ptr1 = next(ptr);
    cout << "The next element: " << *ptr1 << endl;


    set<int>::iterator ptr2 = prev(ptr);
    cout << "The previous element: " << *ptr2 << endl
         << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Set elements are: 1 9 11 14 

The current element: 11
The next element: 14
The previous element: 9

auto keyword

The auto keyword functionality is available in version C++ 11 or higher. As we have seen in previous examples, the syntax to create iterators of various STL containers is very lengthy. The auto keyword simplifies the syntax to a great extent. Apart from this, auto keyword dynamically determines the data type of the assigned value, much like Python programming language. The auto keyword helps in keeping the code clean and tidy. Let us see examples to understand it better.

Program

#include <iostream>
#include <vector>
#include <iterator>
#include <map>

using namespace std;


int main()
{
    // auto keyword determines that the data type of the assigned value is int.
    auto intValue = 2;
    cout << intValue << endl;


    // Create a vector.
    vector<int> vec = {2, 8, 4, 5, 10};


    // auto keyword in this for loop dynamically decides that the data type of vec.begin() as vector container iterator
    cout << "Vector elements are: ";
    for (auto itVec = vec.begin(); itVec != vec.end(); itVec++)
    {
        cout << *itVec << " ";
    }
    cout << endl
         << endl;


    // Create a map container and populate it with some values.
    map<int, int> mapCpp;
    mapCpp[1] = 10;
    mapCpp[2] = 7;
    mapCpp[3] = 5;
    mapCpp[4] = 19;


    cout << "Map elements are:" << endl;
    // auto keyword is also used in range-based loops.
    for (auto value : mapCpp)
    {
        cout << value.first << " " << value.second;
        cout << endl;
    }
    cout << endl;
}
You can also try this code with Online C++ Compiler
Run Code

Output

2
Vector elements are: 2 8 4 5 10 

Map elements are:
1 10
2 7
3 5
4 19
You can also try this code with Online C++ Compiler
Run Code

 

Also check out this article - Pair in C++ and, Dynamic Binding in C++

Key Takeaways

In this blog, we discussed various examples to discuss the concept of iterators and auto keyword in the C++ programming language. We looked at different types of iterators available in C++. We discussed various functions that take these iterators as arguments. We saw how auto keyword helps in keeping the code clean and simple. 

Hence learning never stops, and there is a lot more to learn.

Recommended Readings:

So head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Till then, Happy Learning!

Live masterclass