Practical Range Examples
Real-World Range Iteration Scenarios
Range-based iteration provides powerful solutions across various programming domains. This section explores practical applications demonstrating the versatility of range-based techniques.
Data Processing Examples
Filtering Numeric Collections
#include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> filterEvenNumbers(const std::vector<int>& input) {
std::vector<int> result;
for (const int& num : input) {
if (num % 2 == 0) {
result.push_back(num);
}
}
return result;
}
#include <vector>
#include <algorithm>
std::vector<int> squareNumbers(const std::vector<int>& input) {
std::vector<int> result;
for (const int& num : input) {
result.push_back(num * num);
}
return result;
}
Iteration Patterns
Pattern |
Description |
Use Case |
Sequential |
Linear traversal |
Simple collections |
Filtered |
Conditional iteration |
Data screening |
Transformed |
Element modification |
Data preprocessing |
Aggregated |
Cumulative operations |
Statistical calculations |
Advanced Iteration Techniques
Nested Range Iteration
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (const auto& row : matrix) {
for (const auto& element : row) {
std::cout << element << " ";
}
std::cout << std::endl;
}
Custom Range Generation
class NumberRange {
private:
int start, end;
public:
NumberRange(int s, int e) : start(s), end(e) {}
class Iterator {
private:
int current;
public:
Iterator(int val) : current(val) {}
int operator*() { return current; }
Iterator& operator++() {
++current;
return *this;
}
bool operator!=(const Iterator& other) {
return current != other.current;
}
};
Iterator begin() { return Iterator(start); }
Iterator end() { return Iterator(end); }
};
Iteration Flow Visualization
graph TD
A[Start Range] --> B{Iterate Elements}
B -->|Process| C[Transform/Filter]
C --> D{More Elements?}
D -->|Yes| B
D -->|No| E[End Range]
- Prefer const references for large objects
- Use move semantics when appropriate
- Minimize unnecessary copies
Error Handling Strategies
- Validate input ranges
- Handle empty collections
- Implement robust boundary checks
LabEx Pro Tip
Experiment with different iteration techniques to discover the most efficient approach for your specific use case.
Complex Iteration Example
#include <vector>
#include <numeric>
double calculateWeightedAverage(
const std::vector<double>& values,
const std::vector<double>& weights
) {
double total = 0.0;
double weightSum = 0.0;
for (size_t i = 0; i < values.size(); ++i) {
total += values[i] * weights[i];
weightSum += weights[i];
}
return total / weightSum;
}
Modern C++ Range Extensions
- std::ranges (C++20)
- Ranges library algorithms
- Composable range adaptors
Best Practices
- Choose appropriate iteration method
- Prioritize readability
- Optimize for performance
- Use standard library algorithms