A forward iterator is a concept in C++ that allows us to traverse and manipulate elements in a sequence in a forward-only manner. It provides a way to access and modify elements in a container sequentially, moving from one element to the next.
In C++, the Standard Template Library (STL) provides various iterator types, including forward iterators, to work with different container classes. Forward iterators are mainly used with containers that support sequential access, such as linked lists and forward lists.
Characteristics of Forward Iterators
Forward iterators have the following characteristics:
- They can be dereferenced using the
*
operator to access the value of the current element. - They support the pre-increment (
++
) and post-increment (++
) operators to move to the next element in the sequence. - They can be compared using the equality (
==
) and inequality (!=
) operators to check if two iterators point to the same location.
Example 1: Traversing a Linked List using Forward Iterators
Let’s consider a simple example of traversing a linked list using forward iterators:
#include <iostream>
#include <forward_list>
int main() {
std::forward_list<int> myList = {1, 2, 3, 4, 5};
// Create a forward iterator
std::forward_list<int>::iterator it;
// Traverse the list and print each element
for (it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
In this example, we create a forward iterator named it
and initialize it with the beginning of the myList
forward list. We then use a for
loop to iterate through the list, printing each element using the dereference operator (*
).
The output of this program will be:
1 2 3 4 5
Example 2: Modifying Elements in a Forward List using Forward Iterators
Forward iterators can also be used to modify elements in a container. Let’s see an example of modifying elements in a forward list:
#include <iostream>
#include <forward_list>
int main() {
std::forward_list<int> myList = {1, 2, 3, 4, 5};
// Create a forward iterator
std::forward_list<int>::iterator it;
// Increment each element by 1
for (it = myList.begin(); it != myList.end(); ++it) {
*it += 1;
}
// Print the modified list
for (it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
In this example, we increment each element in the myList
forward list by 1 using a forward iterator. After modifying the elements, we traverse the list again and print the modified values.
The output of this program will be:
2 3 4 5 6
Conclusion
Forward iterators in C++ provide a convenient way to traverse and manipulate elements in a forward-only manner. They are useful when working with containers that support sequential access. By understanding the characteristics and usage of forward iterators, you can efficiently work with various container classes in C++.