Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use C++ 's scope-based for loop

Shulou Source: shulou.com Published: 2022-05-31 21:58:38 10月06日 Update

This article mainly explains "how to use the scope-based for loop of C++". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the scope-based for loop of C++.

1. Concept / / ordinary for loop for (expression 1; expression 2; expression 3) {/ / loop body} / / range-based for loop for (declaration: expression) {/ / loop body} 1.1, ordinary for loop

Its workflow is as follows:

1. Execute expression 1

2. If expression 2 is true, execute the loop body, otherwise jump out of the loop

3. Execute expression 3, which will be repeated in the second step.

This approach requires giving both ends of the container, the beginning and the end.

1.2. range-based for loop

Its workflow is:

1. Copy the elements in expression to declaration

2. Repeat execution

In this way, there is no need to give both ends of the container, the loop will automatically expand with the container as the scope, and the iterator traversal details are shielded in the loop, and the elements in the container are directly extracted for operation.

Expression can be containers, arrays, expressions, initialization lists, etc.

1.3. The difference between the two

Example:

Vector arr {1 cout 2, 3, 4, 5, 6}; / / ordinary for cycle for (auto it = arr.begin (); it! = arr.end (); + + it) cout

Tags: Loops containers ranges expressions Clearing normal elements copy Loop body Association Learning both ends examples content Workflow data method process work influence Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Information MariaDB NVidia Microsoft