Master C++11 Range-Based for Loops: Simplify Your Iterations
This article explains C++11’s range-based for loop, covering its syntax, practical examples for arrays, vectors, maps, and how to use auto type deduction and references to modify elements, while highlighting its advantages over traditional loops and outlining suitable use cases and pitfalls.
1. What is a range for loop?
In C++11 a more concise loop, the range‑based for loop (also called foreach), was introduced. It is used to iterate over containers such as std::vector, std::list, or any iterable object without manually managing indices or iterators.
2. Basic syntax
The syntax of a range‑based for loop is:
for (element_type variable_name : container/array) {
// loop body
}Example 1: Iterate an array
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
// Use range‑based for to iterate the array
for (int num : numbers) {
cout << num << " " ; // Output: 1 2 3 4 5
}
return 0;
}Example 2: Iterate a std::vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> names = {"Alice", "Bob", "Charlie"};
// Iterate vector
for (const string& name : names) {
cout << name << " " ; // Output: Alice Bob Charlie
}
return 0;
}3. Advantages of range‑based for
More concise: no need to manage indices or iterators, reducing code size.
Safer: avoids out‑of‑bounds access.
More readable: clearly expresses the intent to traverse all elements.
Comparison: traditional for loop vs range‑based for loop
Traditional indexed loop:
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}Range‑based for loop:
for (int num : numbers) {
cout << num << " ";
}Clearly, the range‑based for loop is more concise and intuitive.
4. Using auto for type deduction
Since C++11 you can combine the auto keyword to let the compiler deduce the element type, further simplifying code:
vector<double> prices = {9.99, 19.99, 29.99};
for (auto price : prices) {
cout << price << " "; // Output: 9.99 19.99 29.99
}5. Modifying element values (using references)
By default the range‑based for creates copies of elements. To modify the original container, use a reference:
vector<int> nums = {1, 2, 3, 4, 5};
// Modify original array values (must use reference)
for (int& num : nums) {
num *= 2; // each element multiplied by 2
}
for (int num : nums) {
cout << num << " "; // Output: 2 4 6 8 10
}6. Applicable scenarios
The range‑based for loop is suitable for:
Arrays (static or dynamic)
STL containers (vector, list, map, set, etc.)
Custom containers that provide begin() and end()
Example: Iterate a std::map
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> ageMap = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 22}
};
// Iterate map (key‑value pairs)
for (const auto& pair : ageMap) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}7. Precautions
Do not use with containers whose size changes during iteration (e.g., vector.push_back()), as it may invalidate iterators.
Reverse iteration is not supported; for that you need the traditional approach or std::ranges (C++20).
Summary
Range‑based for loops (C++11) provide a simpler, safer way to traverse collections.
Applicable to arrays and STL containers, but not to cases where the container size is modified during iteration.
Combining auto and references can further optimize the code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
