- 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.
- Magento 2 Theme Design(Second Edition)
- .NET 4.0面向對象編程漫談:基礎篇
- 從程序員到架構師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務、多團隊協(xié)同等核心場景實戰(zhàn)
- TypeScript圖形渲染實戰(zhàn):基于WebGL的3D架構與實現(xiàn)
- 深度學習:算法入門與Keras編程實踐
- Ext JS 4 Web Application Development Cookbook
- Spring Boot企業(yè)級項目開發(fā)實戰(zhàn)
- Learning OpenStack Networking(Neutron)(Second Edition)
- INSTANT Sinatra Starter
- 新一代SDN:VMware NSX 網(wǎng)絡原理與實踐
- Unity Character Animation with Mecanim
- Android Studio開發(fā)實戰(zhàn):從零基礎到App上線 (移動開發(fā)叢書)
- 精益軟件開發(fā)管理之道
- 新手學ASP.NET 3.5網(wǎng)絡開發(fā)
- PhoneGap 3.x Mobile Application Development Hotshot