Advanced Iterator Techniques
Iterator Adapters
Reverse Iterators
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Reverse iteration
for (auto rit = numbers.rbegin(); rit != numbers.rend(); ++rit) {
std::cout << *rit << " "; // Prints: 5 4 3 2 1
}
return 0;
}
Stream Iterators
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>
int main() {
std::istringstream input("10 20 30 40 50");
std::vector<int> numbers;
// Copy from input stream to vector
std::copy(
std::istream_iterator<int>(input),
std::istream_iterator<int>(),
std::back_inserter(numbers)
);
return 0;
}
Iterator Operations
Operation |
Description |
Example |
advance() |
Move iterator by n positions |
std::advance(it, 3) |
distance() |
Calculate distance between iterators |
std::distance(begin, end) |
next() |
Get iterator n positions ahead |
auto new_it = std::next(it, 2) |
prev() |
Get iterator n positions behind |
auto prev_it = std::prev(it, 1) |
Algorithm Integration
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
// Find with iterators
auto find_it = std::find(numbers.begin(), numbers.end(), 8);
if (find_it != numbers.end()) {
std::cout << "Found: " << *find_it << std::endl;
}
// Sort using iterators
std::sort(numbers.begin(), numbers.end());
return 0;
}
Iterator Traits
#include <iterator>
#include <vector>
#include <iostream>
template <typename Iterator>
void printIteratorInfo() {
using traits = std::iterator_traits<Iterator>;
std::cout << "Value Type: "
<< typeid(typename traits::value_type).name() << std::endl;
std::cout << "Iterator Category: "
<< typeid(typename traits::iterator_category).name() << std::endl;
}
int main() {
std::vector<int> numbers = {1, 2, 3};
printIteratorInfo<std::vector<int>::iterator>();
return 0;
}
Iterator Validity Flow
stateDiagram-v2
[*] --> Safe: Valid Iterator
Safe --> Invalidation: Container Modification
Invalidation --> Undefined: Dangling Iterator
Undefined --> [*]: Potential Crash
Best Practices
- Always check iterator validity
- Use appropriate iterator categories
- Prefer range-based for loops when possible
- Be cautious with iterator invalidation
Common Mistakes to Avoid
- Dereferencing invalidated iterators
- Incorrect iterator type selection
- Overlooking iterator category constraints
LabEx recommends mastering these advanced techniques for robust C++ programming.