Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report