- Learning C++ Functional Programming
- Wisnu Anggoro
- 257字
- 2021-07-02 20:51:36
Iterating over collections using range-based for loops
In the modern C++, there is a new feature that is augmented to support the for-each technique to iterate over collections. This feature is useful if you want to do something to the elements of a collection or array without caring about the number of elements or the indexes. The syntax of the feature is also simple. Suppose we have an array named arr and we want to iterate each element using the range-based for loop technique; we can use the following syntax:
for (auto a : arr)
// Do something with a
So, we can refactor our preceding begin_end.cpp code to use range-based for loop as we can see in the following code:
/* range_based_for_loop.cpp */
#include <iostream>
auto main() -> int
{
std::cout << "[range_based_for_loop.cpp]" << std::endl;
// Declaring an array
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// Displaying the array elements
// using non-member begin() and end()
std::cout << "Displaying array element using range-based for
loop";
std::cout << std::endl;
for (auto a : arr) std::cout << a << " ";
std::cout << std::endl;
return 0;
}
The syntax we see in the preceding code is simpler now. If we compile the preceding code, we should find no error and, if we run the code, we should see the following output on the console screen:

We now have a new technique to iterate over the collection without caring about the indexes of the collection. We will keep using it in this book.
- Java逍遙游記
- Learning LibGDX Game Development(Second Edition)
- Embedded Linux Projects Using Yocto Project Cookbook
- Boost C++ Application Development Cookbook(Second Edition)
- 架構不再難(全5冊)
- Learning Informatica PowerCenter 10.x(Second Edition)
- PySide 6/PyQt 6快速開發與實戰
- SQL 經典實例
- SQL Server 2016 從入門到實戰(視頻教學版)
- 從零開始學Android開發
- App Inventor 2 Essentials
- Flask Web開發:基于Python的Web應用開發實戰(第2版)
- 進入IT企業必讀的324個Java面試題
- H5匠人手冊:霸屏H5實戰解密
- 計算思維與Python編程