Home >Backend Development >C++ >How Do I Effectively Use Range-Based For Loops in C 11?

How Do I Effectively Use Range-Based For Loops in C 11?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 08:13:09844browse

How Do I Effectively Use Range-Based For Loops in C  11?

Range-based for Loops in C 11

Syntax and Usage

C 11 introduced range-based for loops as a concise and expressive way to iterate over containers. The syntax is:

for (range_declaration : container) {
  // body of the loop
}

where:

  • range_declaration declares a variable to hold each element of the container.
  • container is the container you want to iterate over.

Capturing by Reference or Value

The variable in the range_declaration can be captured by reference or value using the following syntax:

  • auto captures the element by value.
  • auto& captures the element by non-const reference.
  • const auto& captures the element by const reference.

For observing the elements, where you don't need to modify them, you should use const auto&. This prevents unnecessary copies and ensures that the original elements are not modified.

If you want to modify the elements, use auto&.

Note that for containers with proxy iterators (like std::vector), you need to use auto&& to capture the elements by value.

Guidelines for Using Range-based For

Consider the following guidelines when using range-based for:

  • For observing elements:

    • for (const auto& elem : container) (capture by const reference)
    • If elements are cheap to copy (e.g., ints), you can use for (auto elem : container) (capture by value).
  • For modifying elements:

    • for (auto& elem : container) (capture by non-const reference)
    • For proxy iterators (e.g., std::vector), use for (auto&& elem : container) (capture by &&).

Generic Code Considerations

In generic code, where you don't know the type of the elements being iterated over, use:

  • for (const auto& elem : container) for observing elements.
  • for (auto&& elem : container) for modifying elements (works for both regular and proxy iterators).

The above is the detailed content of How Do I Effectively 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