Iterators

Iterators

 
Iterators are objects that are used to access and traverse the elements of data structures like arrays, linked lists, vectors, and other container classes in C++. They are essentially generic pointers that can be used to access elements of a container without using the subscript or index operator.
Iterators are useful because they provide a standard way to access the elements of containers, regardless of the specific implementation of the container. They are also more efficient than using the subscript or index operator, as they do not require random access to elements, which can be especially important for large data structures.
 
#include <iostream> #include <vector> using namespace std; int main() { // Create a vector of integers vector<int> vec = {1, 2, 3, 4, 5}; // Create an iterator to access the first element of the vector vector<int>::iterator iter = vec.begin(); // Use the iterator to access the elements of the vector cout << "Vector elements: "; while (iter != vec.end()) { cout << *iter << " "; iter++; } cout << endl; // Modify elements of the vector using the iterator iter = vec.begin(); *iter = 10; iter++; *iter = 20; // Print the modified vector elements using the iterator cout << "Modified vector elements: "; for (iter = vec.begin(); iter != vec.end(); iter++) { cout << *iter << " "; } cout << endl; return 0; }
In this implementation, we create a vector of integers vec containing elements 1-5. We then create an iterator iter to access the first element of the vector using the begin() function. We use the iterator to traverse the elements of the vector using a while loop, and we print the elements of the vector using the *iter operator.
Using the iterator, we then modify the first two elements of the vector to be 10 and 20 using the *iter operator, and we print the modified elements of the vector using a for loop and the begin() and end() functions of the vector.
This implementation shows how iterators can be used to access and modify the elements of containers in C++. It demonstrates the advantages of using iterators over the subscript or index operator, as the iterator can be used to traverse the container in a flexible and efficient manner without requiring random access to elements of the data structure.