Home >Backend Development >C++ >How to Choose the Right C 11 Range-Based `for` Loop Syntax?

How to Choose the Right C 11 Range-Based `for` Loop Syntax?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 05:55:09502browse

How to Choose the Right C  11 Range-Based `for` Loop Syntax?

Understanding Range-Based for Syntax in C 11

Range-based for loops in C 11 provide a simplified syntax for iterating over containers. The syntax varies depending on whether you intend to observe or modify the container's elements.

For Observing Elements

To observe elements without modifying them, the recommended syntax is:

for (const auto& elem : container)

This syntax captures the elements by const reference, avoiding unnecessary copies in cases where the objects are expensive to copy.

For Modifying Elements

If you need to modify elements in place, the syntax is:

for (auto& elem : container)

This syntax captures the elements by non-const reference, allowing you to modify them in the loop body.

Special Case: Proxy Iterators

However, for containers that use proxy iterators (such as std::vector), a different syntax is required to modify elements:

for (auto&& elem : container)

This syntax uses the "&&" type modifier to correctly work with proxy iterators.

Summary

  • For observing elements, use for (const auto& elem : container) or for (auto elem : container) if copying is inexpensive.
  • For modifying elements, use for (auto& elem : container) or for (auto&& elem : container) for proxy iterators.
  • In generic code, prefer using the const reference syntax for observing and auto&& for modifying to handle both standard and proxy iterators gracefully.

The above is the detailed content of How to Choose the Right C 11 Range-Based `for` Loop Syntax?. 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