How to correctly use the range-based for loop in C 11
The range-based for loop is a concise and powerful Iterator traversal mechanism that has been introduced in C 11 introduced in. It is used to iterate over a container or other iterable sequence and reference elements in the sequence through one or more variables. Here's how to use a range-based for loop correctly:
Syntax
for (auto elem : container) {
// 代码体
}
Where:
- The auto keyword means that the compiler will automatically infer the element type.
- elem is the iterator variable for the elements in the loop.
- container is the container or iterable sequence to be iterated over.
Element Capture Mode
When using a range-based for loop, you can choose one of the following three element capture modes:
-
Press Value capture (auto elem): Creates a local copy of an element. This works for types whose elements are cheap to copy (e.g. int, double, etc.).
-
Capture by reference (auto&elem): Directly reference the element in the container. This is used for modifying elements or types where copying needs to be avoided.
-
Capture proxy by reference (auto&&elem): For traversing a container using a "proxy iterator" (e.g. std::vector).
Observe or modify
Range-based for loops can be used for two main purposes:
-
Observe elements: Use const auto&elem captures elements to ensure the original element is not modified.
-
Modify element: Use auto&elem to capture the element to modify the original element directly.
Guidelines
To correctly use range-based for For loops, consider the following guidelines:
- For observed elements, use:
for (const auto& elem : container) // 按引用捕获常量
- For modified elements, use:
for (auto& elem : container) // 按引用捕获
- If the container uses "proxy Iterator", use:
for (auto&& elem : container) // 按引用捕获 proxy
Notes in Generic Code
In generic code, it is recommended to use const auto&elem to capture elements for observation, and auto&&elem captures elements for modification, as these methods work with various types of containers and elements.
The above is the detailed content of How Can I Correctly Use Range-Based For Loops in C 11?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn