An iterator in C++ is a pointer-like object that points to an element of the STL container. They are generally used to loop through the contents of the STL container in C++. The main advantage of STL iterators is that they make the STL algorithms independent of the type of container used. We can just pass the iterator to the container elements instead of the container itself to the STL algorithms.
Iterator Declaration
Each container in C++ STL has its own iterator. So, we have to declare an iterator as:
C++
where,
- type: Type of container for which the iterator is declared.
- it: Name assigned to iterator object.
We can then initialize it by assigning some valid iterator. If we already have an iterator to be assigned at the time of delcaration, then we can skip the type declaration using the auto keyword.
C++
where, iter is the iterator assigned to the newly created it iterator.
Our C++ Course covers the use of iterators in the STL, ensuring you understand how to traverse different container types.
Example of Iterators
The below program illustrates how to use the iterator to traverse the vector container:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// Defining an iterator pointing to
// the beginning of the vector
vector<int>::iterator first =
v.begin();
// Defining an iterator pointing
// to the end of the vector
vector<int>::iterator last =
v.end();
// Iterating the whole vector
while(first != last) {
cout << *first << " ";
first++;
}
return 0;
}
As you may have noticed, we have used vector::begin() and vector::end() function. These functions are the member functions to std::vector that returns the iterator to the first and one element after the last element of the vector. We use the iterators return be these functions to iterate the vectors.
Container Iterator Functions
C++ STL provides some member functions in STL container that return the iterators to at least the first and the last element. These member functions are defined in almost all of the STL container (leaving some limited access containers like stack, queue) with the same name for consistency.
The following table lists all methods that returns the iterator to the containers:
Iterator Function | Return Value |
---|
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. |
For Example, if vec is the name of the vector, then we can use the above methods as shown below:
C++
vec.begin(), vec.rbegin(),
vec.cbegin(), vec.crbegin()
vec.end(), vec.rend(),
vec.cend(), vec.crend()
Iterators Operations
Just like pointer arithmetic, there are some operations that are allowed on C++ iterators. They are used to provide different functionalities that increases the importance of iterators. There are 5 valid iterator operations in C++:
- Dereferencing Iterators
- Incrementing/Decrementing Iterators
- Adding/Subtracting Integer to Iterators
- Subtracting Another Iterator
- Comparing Iterators
Dereferencing Iterators
Dereferencing operation allows the users to access or update the value of the element pointed by the iterator. We use the (*) indirection operator to dereference iterators just like pointers.
C++
// Access
*it;
// Update
*it = new_val;
where new_val is the new value assigned to the element pointed by iterator it.
Incrementing/Decrementing Iterators
We can increment or decrement the iterator by 1 using (++) or (--) operators respectively. Increment operation moves the iterator to the next element in the container while the decrement operation moves the iterator to the previous element.
C++
it++; // post-increment
++it; // pre-increment
it--; // post-decrement
--it; // pre-decrement
Adding/Subtracting Integer to Iterators
We can also add or subtract an integer value from the iterators. It will more the iterator next or previous position according to the added integer value.
C++
// Addition
it + int_val;
// Subtraction
it - int_val;
where int_val is the integer values that is being added or subtracted from the iterator it.
Subtracting Another Iterator
We can subtract one iterator from another to find the distance (or the number of elements) between the memory they are pointing to.
C++
Comparing Iterators
We can also test the two iterators of the same type against each other to find the relationship between them. We can use the relational operators like (==) equality and (!=) inequality operators along with other relational operators such as <, >, <=, >=.
C++
it1 != it2 // Equal to
it1 == it2 // Not equal to
it1 > it2 // Greater than
it1 < it2 // Less than
it1 >= it2 // Greater than equal to
it1 <= it2 // Less than equal to
Types of Iterators in C++
STL iterators can be divided on the basis of the operations that can be performed on them. There are 5 main types of iterators in C++ which as listed in the below table along with supported containers and supported iterator operations.
Iterator | Description | Supported Containers | Supported Operations |
---|
Input Iterator | It is a one-way iterator used to read the values. | Input Stream | Dereferencing, Increment, Equality |
---|
Output Iterator | It is also a one-way iterator but used to assign the values. It cannot access the values. | Output Stream | Dereferencing (write only), Increment |
---|
Forward Iterators | It can access and as well as assign the values. It is the combination of both input and output iterator. | forward_list, unordered_map, unordered_set | Dereferencing, Increment, Equality |
---|
Bidirectional Iterators | It can move in both direction either in forward or backward. The containers like list, set, and multimap supports bidirectional iterators. | list, map, set, multimap, multiset | Dereferencing, Increment/Decrement, Equality |
---|
Random Access Iterators | Random-access iterators are iterators that can be used to access elements at distance from the element they point to, offering the same functionality as pointers. | vector, deque, array, string | All |
---|
As we may have noticed from the above table, apart from the input and output iterators, as we go down the table, the iterator type contains the features of above iterator along with some new features.
Iterator Adaptors
Iterator adaptors in C++ are the special type of iterators that are built over traditional iterators to provide specialized functionality. There are many iterator adaptors in C++ some of which are given below:
Iterator Adaptors Type | Description |
---|
Reverse Iterator | The reverse iterator is built over bidirectional or above type of operator and allows users to traverse the container in the reverse direction. |
Stream Iterators | The stream iterators namely, istream and ostream iterators are built on the input and output iterators respectively. These iterators allow the users to use the streams as containers. |
Move Iterators | Move iterators are used to introduce the move semantics in STL algorithms. The move iterators move the ownership of the copied container data to the copying container without creating the extra copies. |
Inserter Iterator | The insertor iterators allows you to insert the given elements at some position in the container. There are three insertor iterators in C++: - back_insert_iterator: Inserts at the back of the container.
- front_insert_iterator: Inserts at the front of the container.
- insert_iterator: Inserts at anywhere in the container.
These iterators can be created using back_inserter(), front_inserter(), inserter() functions in C++. |
Iterator Utility Functions in C++
C++ STL provide the various function to simplify the working with iterators. They are listed in the below table:
Function | Description | Syntax |
---|
std::advance | Advances an iterator by a specific number of positions. | advance(it, n) |
---|
std::next | Returns the iterator that is a specified number of positions ahead of the given iterator. | next(it, n) |
---|
std::prev | Returns the iterator that is a specified number of positions behind the given iterator. | prev(it, n) |
---|
std::distance | Returns the number of elements between two iterators. | distance(it1, it2) |
---|
std::begin | Returns an iterator to the first element of the given container. | begin(container) |
---|
std::end | Returns an iterator to the element following the last element of the given container. | end(container) |
---|
std::rbegin | Returns a reverse iterator to the last element of the given container. | rbegin(container) |
---|
std::rend | Returns a reverse iterator to the element preceding the first element of the given container. | rend(container) |
---|
std::inserter | Creates an insert iterator that inserts elements into a container at a specified position. | inserter(container, position) |
---|
std::back_inserter | Creates a back insert iterator that appends elements to the end of a container. | back_inserter(container) |
---|
std::front_inserter | Creates a front insert iterator that inserts elements at the front of a container. | front_inserter(container) |
---|
Applications of Iterators with Examples
Iterators are extensively used in C++ for many different purposes while working with STL containers and algorithms. Following are some primary applications of iterators in C++ which their code examples:
Traversing Containers
Traversing STL containers is the most basic application of iterators. In this, we use the begin() and end() functions to get the begin and end iterators to traverse the whole container. Basically, we keep incrementing the begin iterator till it is not equal to the end.
Example
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {10, 20, 30,
40, 50};
// Iterator to the beginning
// of the set
auto it = s.begin();
// Iterating through the
// entire set
while (it != s.end()) {
// Dereferencing iterator
// to access value
cout << *it << " ";
// Incrementing the
// iterator
it++;
}
return 0;
}
As shown in the code above, we traverse the set container. Similarly, we can use the same approach to traverse any container.
Reversing a Container
Reverse iterators allow you to traverse a container from the end to the beginning without needing to manually handling the reversal.
Example
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vec = {10, 20, 30,
40, 50};
// Defining reverse iterators
// pointing to the reverse
// beginning of vec
auto it = vec.rbegin();
// Iterating the whole
// vector in reverse
while (it != vec.rend()) {
cout << *it << " ";
it++;
}
return 0;
}
Container-Independent Algorithms
Iterators allow algorithms to work with any container type, making functions like std::sort(), std::find(), and std::for_each() more flexible. You can pass iterators instead of the actual container.
Example
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vec = {30, 10, 40,
10, 50};
multiset<int> ms = {10, 30, 10,
20, 40, 10};
// Using the std::count() algorithm to count
// the number of occurences of 10 in vector
// and multiset using iterator
cout << "10s in Vector: "
<< count(vec.begin(),
vec.end(), 10) << endl;
cout << "10s in Multiset: "
<< count(ms.begin(),
ms.end(), 10);
return 0;
}
Output10s in Vector: 2
10s in Multiset: 3
Additional Applications of Iterators
There are more applications of STL iterators:
- Distance Calculation: Using std::distance(), iterators help calculate the number of elements between two positions in a container.
- Stream Iteration: Stream iterators allow you to treat input/output streams like containers, making it easier to read from and write to streams using STL algorithms.
- Move Semantics in STL Algorithms: Move iterators introduces the move semantics in STL algorithms which helps in increasing performance and efficiency by avoiding unnecessary copying. The data will be moved according to the rules of move semantics.
- Custom Iterators for Data Structures: Custom iterators can be implemented for non-STL data structures like trees or graphs to provide the support for STL algorithms and many other features. We may need to follow a few set of rules and conventions to provide proper incrementing, decrementing, and other operations.
Iterators in C++ STL
Iterators in C++ STL
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem