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

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.

主站蜘蛛池模板: 师宗县| 仁怀市| 长宁区| 东乡县| 宣威市| 邵武市| 清水县| 县级市| 温泉县| 两当县| 普宁市| 米泉市| 南华县| 长顺县| 宜兴市| 邯郸县| 洪江市| 五大连池市| 寿阳县| 西城区| 衡阳市| 禹州市| 临清市| 西和县| 衢州市| 新化县| 姚安县| 吴忠市| 榕江县| 榆社县| 长岛县| 南城县| 牡丹江市| 罗定市| 兴文县| 盐池县| 家居| 营口市| 郓城县| 财经| 罗定市|