Iterator operations in C++ provide various ways to work with elements stored in STL containers. These operations make iterators powerful tools for traversing, accessing, and manipulating container data efficiently.
- Support operations such as dereferencing, increment/decrement, arithmetic, and comparison.
- Enable efficient navigation and manipulation of elements within containers.
Basic Iterator Operations
The following are the five fundamental operations supported by C++ iterators:
1. 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.
Syntax
*itr; // Access
*itr = new_val; // Update
where new_val is the value to be assigned to the element pointed by itr.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> vec = {'a', 'b', 'c', 'd'};
// Create an iterator pointing to the second
// element (index 1)
auto itr = vec.begin() + 1;
// Dereference the iterator to get the value
// at the second position
cout << "Second Element: " << *itr << endl;
// Modify the value of the second element using
// the iterator
*itr = 'x';
cout << "Second Element After Update: " << *itr;
return 0;
}
Output
Second Element: b Second Element After Update: x
Explanation: The iterator first accesses the element 'b' and then updates it to 'x' using dereferencing.
2. Incrementing/Decrementing Iterators
Iterators can be moved forward or backward using increment (++) and decrement (--) operators.
Syntax
itr++; // post-increment
++itr; // pre-incrementitr--; // post-decrement
--itr; // pre-decrement
pre and post increment/decrement basically does the same thing with small difference.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Initialize a vector of characters
vector<char> vec = {'a', 'b', 'c', 'd'};
// Create an iterator pointing to the second
// element (index 1)
auto itr = vec.begin() + 1;
// Dereference the iterator to get the value
// at the second position
cout << "Second Element: " << *itr << endl;
// Increment the iterator to point to the next
// element
itr++;
cout << "After Increment, Element: " << *itr
<< endl;
// Decrement the iterator to point back to the
// previous element
itr--;
cout << "After Decrement, Element: " << *itr;
return 0;
}
Output
Second Element: b After Increment, Element: c After Decrement, Element: b
Explanation: Increment moves the iterator to the next element, while decrement moves it back to the previous element.
3. Adding/Subtracting Integer
Some iterators support adding or subtracting integer values to move multiple positions at once.
Syntax
itr + int_val; // Addition
itr - int_val; // Subtraction
where n is an integer.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> vec = {'a', 'b', 'c', 'd'};
auto itr = vec.begin() + 1;
itr = itr + 2;
cout << *itr << endl;
itr = itr - 3;
cout << *itr;
return 0;
}
Output
d a
Explanation: Adding an integer moves the iterator forward, while subtracting moves it backward.
4. Subtraction of Iterators
Two iterators belonging to the same container can be subtracted to determine the distance between them.
Syntax
itr1 - itr2
where itr1 and itr2 are the iterators to the same container as subtracting iterator of different containers is not meaningful is most cases.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Initialize a vector of characters
vector<char> vec = {'a', 'b', 'c', 'd'};
// Iterator pointing to the first element
auto itr1 = vec.begin();
// Iterator pointing to the last element
auto itr2 = vec.end() - 1;
// Subtract itr1 from itr2 to get the number of
// elements between them
cout << "Elements between itr1 and itr2: " <<
itr2 - itr1;;
return 0;
}
Output
Elements between itr1 and itr2: 3
Explanation: The iterator itr1 points to the first element 'a' and iterator itr2 points to the last element 'd'. Subtracting itr1 from itr2, we get 3 which is the number of elements between itr1 and itr2 inclusive itr2.
5. Comparing Iterators
Iterators can be compared using equality and relational operators.
Syntax
itr1 != itr2 // Equal to
itr1 == itr2 // Not equal toitr1 > itr2 // Greater than
itr1 < itr2 // Less than
itr1 >= itr2 // Greater than equal to
itr1 <= itr2 // Less than equal to
The equality operators generally have variety of use cases, but relational operators are generally used for iterators belonging to same container.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> vec = {'a', 'b', 'c', 'd'};
// Iterator pointing to the first element
auto itr1 = vec.begin();
// Iterator pointing to the last element
auto itr2 = vec.end() - 1;
// Check equality using == operator
if (itr1 == itr2)
cout << "itr1 and itr2 are equal." << endl;
else
cout << "itr1 and itr2 are not equal." << endl;
// Check relational comparison using <, >, <=, >= operators
if (itr1 < itr2)
cout << "itr1 is less than itr2." << endl;
if (itr2 > itr1)
cout << "itr2 is greater than itr1." << endl;
// Iterator pointing to the same position as itr1
auto itr3 = vec.begin();
// Check equality with itr3
if (itr1 == itr3)
cout << "itr1 and itr3 are equal." << endl;
else
cout << "itr1 and itr3 are not equal." << endl;
return 0;
}
Output
itr1 and itr2 are not equal. itr1 is less than itr2. itr2 is greater than itr1. itr1 and itr3 are equal.
Explanation: itr1 and itr2 point to different elements, so itr1 == itr2 evaluates to false. Since itr3 points to the same element as itr1, the comparison itr1 == itr3 evaluates to true.
Note: All these operation does not perform any bound checking, so it may lead point to invalid memory location if not handled properly.
Iterator Types and Supported Operations
Not all iterators support all operations. The operations available depend on the iterator category.
Iterator | Supported Containers | Supported Operations |
|---|---|---|
Input Stream | Dereferencing, Increment, Equality | |
Output Stream | Dereferencing (write only), Increment | |
forward_list, unordered_map, unordered_set | Dereferencing, Increment, Equality | |
list, map, set, multimap, multiset | Dereference, Increment, Decrement, Equality | |
vector, deque, array, string | All iterator arithmetic operations |
Iterator Utility Functions
The STL provides several utility functions for performing iterator operations.
Function | Description | Syntax |
|---|---|---|
Moves an iterator by a specified number of positions | std::advance(itr, n); | |
Returns an iterator advanced by n positions | temp_itr = std::next(itr, n); | |
Returns an iterator moved backward by n positions | temp_itr = std::prev(itr, n); | |
Returns the number of elements between two iterators | diff = std::distance(itr1, itr2); |