Table of contents
1.
Introduction
2.
What are Iterators in C++?
3.
Operations of the iterator
4.
Types of iterators
5.
Iterator Adaptors
6.
Example of Iterators
7.
Iterator Utility Functions in C++
8.
Applications of Iterators with Examples
8.1.
1. Accessing Container Elements
8.2.
2. Reversing a Container
8.3.
3. Inserting Elements at Specific Positions
9.
Advantages of Iterators
10.
Disadvantages of Iterators
11.
Frequently Asked Questions
11.1.
What is the advantage of the storage memory hierarchy architecture?
11.2.
Which is a more critical, processor or RAM?
11.3.
What will happen if RAM is not available in a computer system?
11.4.
What is the main difference between memory and CPU?
11.5.
How is RAM being used in computer architecture?
12.
Conclusion
Last Updated: Dec 14, 2024
Easy

Iterators in C++

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

Introduction

In C++ programming, iterators play a crucial role in navigating through containers efficiently. They provide a standardized way to access and manipulate data stored in various container types, abstracting the complexity of underlying data structures. This blog explores the concept of iterators, their types, and practical usage, making it easier to harness their full potential in your C++ programs.

Iterators in C++

What are Iterators in C++?

In computer programming, an iterator is a pointer that enables a programmer to traverse a container. It makes the algorithm independent of the type of container used, and it provides a generic approach to traverse through the elements of a container.

Now let’s understand the operators in the iterator.

Operations of the iterator

OperationDescription
begin()Returns an iterator to the start of the given container.
end()Returns an iterator to the end of the given container.
advance()Increments the iterator position by the specified number of steps mentioned in its arguments.
next()Returns the new iterator after advancing the current iterator by the specified number of positions.
prev()Returns the new iterator after decrementing the current iterator by the specified number of positions.
inserter()Inserts elements at a specified position in the container. Accepts two arguments: the container and the iterator pointing to the desired insertion position.

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

Types of iterators

There are mainly five types of iterators:

Type of IteratorDescriptionOperators Used
Input IteratorUsed to access elements from the container without modifying their values.++, ==, !=, *
Output IteratorUsed to modify the value of a container without reading its value (write-only iterator).++, =
Forward IteratorUsed to read and write to a container; it is a multi-pass iterator.=, ==, !=, ++
Bidirectional IteratorExtends the forward iterator with the ability to move backward using the decrement operator.=, ++, ==, !=, --
Random Access IteratorExtends the bidirectional iterator with the ability to provide random access to elements using pointer addition and subtraction.=, ++, --, ==, !=, Pointer Addition/Subtraction

Iterator Adaptors

AdaptorDescriptionUsage
reverse_iteratorAllows iterating through a container in reverse order.std::reverse_iterator<IteratorType>
back_insert_iteratorInserts elements at the end of a container by wrapping the push_back method.std::back_inserter(container)
front_insert_iteratorInserts elements at the beginning of a container by wrapping the push_front method.std::front_inserter(container)
insert_iteratorInserts elements at a specified position within a container using the iterator provided.std::inserter(container, position)

Example of Iterators

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30, 40, 50};
    vector<int>::iterator it;

    cout << "Elements of the vector: ";
    for (it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << " ";
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation:

  • A vector of integers is created with initial values.
  • An iterator (it) is declared to traverse the vector.
  • The begin() method initializes the iterator to the start of the vector, while the end() marks its termination.
  • The loop prints each element by dereferencing the iterator using *it.

Iterator Utility Functions in C++

  • std::advance: Moves an iterator forward by a specified number of steps.
  • std::distance: Calculates the number of elements between two iterators.
  • std::next: Returns an iterator advanced by a given number of positions.
  • std::prev: Returns an iterator decremented by a given number of positions.
  • std::inserter: Allows inserting elements into a container at a specific position.

Applications of Iterators with Examples

1. Accessing Container Elements

#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> numbers = {1, 2, 3, 4, 5};
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << " ";
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation: Iterators are used to traverse the list and print each element.

2. Reversing a Container

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};
    reverse(numbers.begin(), numbers.end());

    for (int num : numbers) {
        cout << num << " ";
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation: The reverse function uses iterators to modify the order of elements in the vector.

3. Inserting Elements at Specific Positions

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

int main() {
    vector<int> numbers = {1, 2, 3};
    auto it = numbers.begin();
    advance(it, 1); // Move iterator to the second position

    numbers.insert(it, 10);

    for (int num : numbers) {
        cout << num << " ";
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation: The advance function moves the iterator to the desired position, and the insert function places the new element there.

Advantages of Iterators

Following are the advantages of an iterator:

  • Code Reusability: For the reusability of code, we use iterators. However, we first use iterators to access the list element elements.
  • Ease in programming: It is better to use iterators rather than utilizing a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, we need to keep track of the number of elements added at the runtime, but this would not happen in the case of an iterator.
  • Dynamic Processing: C++ iterators provide the facility to dynamically add or delete the data.

Disadvantages of Iterators

Following are the disadvantages of an iterator:

  • Iterators won't work in the simultaneous movement of data structure from one to another.
  • If we're going to update the structure being iterated, an iterator won't allow us to do so because of how it stores the position.
  • The iterator will not work if we backtrack while processing through a list

We will close the article now with faqs since you get the overall idea of iterators.

Frequently Asked Questions

What is the advantage of the storage memory hierarchy architecture?

A Hierarchical Memory System – or Memory Hierarchy for short – is an economical solution to provide computer programs with (virtually) unlimited fast memory, taking advantage of the locality and cost-performance of memory technology.

Which is a more critical, processor or RAM?

RAM is the core of any computer or smartphone, and in most cases, more is always better. RAM is as important as the processor. The exact amount of RAM on your smartphone or computer enhances the performance and supports various types of software.

What will happen if RAM is not available in a computer system?

RAM is not available on the computer; it will not run or start. If you mean when it runs out of available RAM, the computer gets slow, and no paging is being used or virtual RAM, your computer will lock up and stop running.

What is the main difference between memory and CPU?

CPU is the Central Processing Unit, and it performs calculations (or, more precisely, computations). At the same time, memory is the temporary data storage space used by active processes being executed by the CPU.

How is RAM being used in computer architecture?

Because of its speed, RAM is used to process information immediately. When you want to accomplish a specific task, computer operating systems load data from the hard disk into RAM to process it, such as sort a spreadsheet or display it on screen.

Conclusion

This article taught us about the Iterators, the operators in iterators, and their types. And at the end of the blog, we also learned the pros and cons of iterators. To read more about the STL in C++, Visit Here.

Recommended Readings:

We hope that this blog has helped you enhance your knowledge regarding Methods in C# and if you would like to learn more, check out our articles in the code360 library. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass