Practical Usage Patterns
Filtering Elements
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Filter even numbers
for (int num : numbers) {
if (num % 2 == 0) {
std::cout << num << " ";
}
}
return 0;
}
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Square each number
for (int& num : numbers) {
num = num * num;
}
// Print transformed numbers
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Working with Complex Data Structures
Nested Iteration
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Iterate through 2D vector
for (const auto& row : matrix) {
for (int num : row) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
Iteration Patterns
graph TD
A[Iteration Patterns] --> B[Simple Linear Iteration]
A --> C[Nested Iteration]
A --> D[Conditional Iteration]
A --> E[Transformation]
Advanced Iteration Techniques
Iterating with Index
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "cherry"};
// Iterate with index
for (size_t i = 0; i < fruits.size(); ++i) {
std::cout << "Index " << i << ": " << fruits[i] << std::endl;
}
return 0;
}
Common Use Cases
Use Case |
Description |
Example |
Data Processing |
Transform or filter collections |
Squaring numbers |
Configuration |
Iterate through settings |
Reading config parameters |
Initialization |
Populate data structures |
Filling arrays or vectors |
Best Practices
- Use const references for read-only iteration
- Avoid modifying the container during iteration
- Choose the most appropriate iteration method
graph TD
A[Performance] --> B[By Value]
A --> C[By Reference]
A --> D[Const Reference]
B --> E[Overhead of Copying]
C --> F[Direct Modification]
D --> G[Most Efficient for Large Objects]
Conclusion
Range-based for loops provide powerful and flexible iteration mechanisms. LabEx recommends mastering these patterns to write more expressive and efficient C++ code.