Introduction
In one of the previous lessons (cpp_008: for Loops in C++), we covered the basics of for loops, including their syntax and common use cases.
In this lesson, we’ll explore different types of for loops in C++, specifically focusing on range-based for loops and reference-based for loops. These loops provide cleaner, more efficient, and safer ways to iterate over collections like arrays, vectors, and other containers. We’ll explain why and when to use these loops, along with examples and outputs to help beginners understand these concepts easily.
If you’re not familiar with vectors in C++, I recommend checking out our previous lessons on arrays and vectors before diving into this post.
🔹 Range-Based For Loops
🔸 General Rule and Syntax
Range-based for loops, simplify iterating over collections like arrays, vectors, and other containers. The syntax is:
for (type variable : collection) {
// Code block to execute
}
Here, type is the data type of the elements in the collection, variable is the loop variable, and collection is the container (e.g., array, vector).
🔸 Explanation of the Syntax
- Automatic Iteration:
The loop automatically iterates over each element in the collection, eliminating the need for manual indexing. - Read-Only by Default:
By default, the loop variable (variable) is a copy of the element in the collection. This means modifications to variable do not affect the original collection. - Cleaner Code:
Range-based loops reduce boilerplate code, making it easier to read and maintain.
🔸 Example 1: Range-Based Loop with Vectors
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
cout << "Vector elements: ";
for (int num : vec) {
cout << num << " ";
}
return 0;
}
Output:
Vector elements: 1 2 3 4 5
Explanation:
- The loop iterates over each element in the vector vec.
- The variable num is a copy of the current element, so changes to num do not affect vec.
🔹 Reference-Based For Loops
🔸 General Rule and Syntax
When you want to modify the elements of a collection during iteration, you can use a reference-based for loop. The syntax is:
for (type& variable : collection) {
// Code block to execute
}
Here, type& indicates that variable is a reference to the elements in the collection.
🔸 Explanation of the Syntax
- Reference Mechanism:
The loop variable (variable) is a reference to the actual element in the collection, not a copy. - Modifications Affect the Original Collection:
Changes made to variable inside the loop will modify the original collection. - Efficiency:
Using references avoids copying elements, which is especially beneficial for large collections or complex objects.
🔸 Example 2: Reference-Based Loop with Vectors
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
cout << "Original vector: ";
for (int num : vec) {
cout << num << " ";
}
cout << endl;
// Modify the vector using a reference-based loop
for (int& num : vec) {
num *= 2; // Double each element
}
cout << "Modified vector: ";
for (int num : vec) {
cout << num << " ";
}
return 0;
}
Output:
Original vector: 1 2 3 4 5
Modified vector: 2 4 6 8 10
Explanation:
- The first loop prints the original vector.
- The second loop uses a reference (int& num) to double each element in the vector.
- The changes are reflected in the original vector.
🔹 Const Reference-Based For Loops
🔸 General Rule and Syntax
When you want to iterate over a collection without modifying its elements, you can use a const reference-based for loop. The syntax is:
for (const type& variable : collection) {
// Code block to execute
}
Here, const type& ensures that variable is a read-only reference to the elements in the collection.
🔸 Explanation of the Syntax
- Read-Only Access:
The loop variable (variable) cannot be modified, ensuring the collection remains unchanged. - Efficiency:
Using const references avoids copying elements while preventing accidental modifications. - Safety:
This approach is ideal for scenarios where you need to ensure data integrity.
🔸 Example 3: Const Reference-Based Loop with Vectors
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
cout << "Vector elements (read-only): ";
for (const int& num : vec) {
cout << num << " ";
}
return 0;
}
Output:
Vector elements (read-only): 1 2 3 4 5
Explanation:
- The loop iterates over the vector using a const reference.
- The elements cannot be modified inside the loop, ensuring the vector remains unchanged.
🔹 When to Use Each Type of Loop

🔹 Key Takeaways
- Range-Based Loops: Simplify iteration over collections but work with copies of elements by default.
- Reference-Based Loops: Allow modification of the original collection and avoid copying elements.
- Const Reference-Based Loops: Provide efficient, read-only access to collections.
By understanding these different types of for loops, you can write cleaner, more efficient, and safer C++ code.
'C++ Beginner' 카테고리의 다른 글
cpp_015: STL Array in C++ (0) | 2025.03.10 |
---|---|
cpp_014: Passing Arrays and Vectors to Functions in C++ - Syntax and Examples (0) | 2025.03.09 |
cpp_013: Arrays vs. Vectors in C++ - Understanding the Differences with Examples (0) | 2025.02.26 |
cpp_012: Introduction to Vectors in C++ (0) | 2025.02.17 |
cpp_012: Multidimensional Arrays in C++ (0) | 2025.02.08 |