Home >Backend Development >C++ >How Should I Use C 11's Range-Based For Loop for Observing and Modifying Container Elements?

How Should I Use C 11's Range-Based For Loop for Observing and Modifying Container Elements?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 03:55:12271browse

How Should I Use C  11's Range-Based For Loop for Observing and Modifying Container Elements?

How should C 11's range-based for be used?

Syntax:

The syntax for C 11's range-based for loop varies depending on the desired operation on the container elements:

Observing elements:

  • For just observing the elements, capture by const reference: for (const auto& elem : container)

    • For cheap-to-copy types, simplify to: for (auto elem : container) if desired.

Modifying elements:

  • Capture by (non-const) reference: for (auto& elem : container)

    • For containers with proxy iterators (like std::vector), use: for (auto&& elem : container)

Guidelines:

Observing vs. Modifying

Observing:

  • The goal is to access elements without modifying them.
  • Use for (const auto& elem : container) or for (auto elem : container) when elements are cheap to copy.

Modifying:

  • The goal is to modify elements in place.
  • Use for (auto& elem : container).
  • For proxy iterators, use: for (auto&& elem : container).

Generic Code:

In generic code, to ensure compatibility with diverse types and containers:

Observing:

  • Always use for (const auto& elem : container).

Modifying:

  • Use for (auto&& elem : container).

The above is the detailed content of How Should I Use C 11's Range-Based For Loop for Observing and Modifying Container Elements?. 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