官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 泾川县| 长汀县| 汶川县| 筠连县| 嘉兴市| 错那县| 崇州市| 常熟市| 永胜县| 沂源县| 长丰县| 内乡县| 大姚县| 元氏县| 视频| 扶沟县| 乐昌市| 广汉市| 广西| 朔州市| 四子王旗| 三门峡市| 从江县| 视频| 府谷县| 马关县| 徐水县| 驻马店市| 高安市| 上蔡县| 辽宁省| 栾城县| 海南省| 阿鲁科尔沁旗| 长泰县| 遵化市| 美姑县| 罗山县| 庄浪县| 福建省| 渭源县|