for
loopsThe range-based for loop, introduced in C++11, is a simplified way to iterate over elements in a collection (such as arrays, vectors, or any other container that supports iteration). It provides a more concise and readable alternative to traditional for loops, especially when working with containers from the Standard Template Library (STL).
The syntax for a range-based for loop is:
for (declaration : expression) {
// loop body
}
Here's a simple example of using a range-based for loop to iterate over the elements of a std::vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Range-based for loop to iterate over the vector
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
1 2 3 4 5
for (int n : numbers)
: This range-based for loop iterates over each element in the numbers vector, with n being a copy of each element.std::cout << n << " ";
: Each element is printed out, separated by a space.When iterating over containers that should not be modified, you can use const references:
#include <iostream>
#include <vector>
int main() {
const std::vector<int> numbers = {1, 2, 3, 4, 5};
// Range-based for loop with a const reference
for (const int& n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Expected Output
1 2 3 4 5
const int& n
: This ensures that the elements are not modified within the loop. It is particularly useful when working with constant containers or when you want to prevent accidental modifications.Range-based for loops also work with arrays, both static and dynamic:
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
// Range-based for loop to iterate over an array
for (int n : arr) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
10 20 30 40 50
auto
Keyword in Range-Based For LoopsYou can simplify the loop even further using the auto keyword, allowing the compiler to deduce the type:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Range-based for loop using auto
for (auto& n : numbers) {
n += 5;
}
for (const auto& n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
6 7 8 9 10
auto& n
: Automatically deduces that n should be an int&
, based on the type of the elements in numbers.const auto& n
: Automatically deduces that n
should be a const int&
.begin()
and end()
).Range-based for loops simplify the iteration over containers and arrays in C++, making the code more concise and easier to read. They are versatile and can be combined with references, the const keyword, and the auto keyword to create flexible and efficient loops that avoid common pitfalls associated with traditional loop constructs. This feature is especially useful in modern C++ programming, where readability and safety are key concerns.
Previous Page | Course Schedule | Course Content