Skip to content

docs: add ranged based for loop concept files #945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions concepts/ranged-loops/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"blurb": "Range-based loops in C++ provide a concise and readable way to iterate over elements in a container, eliminating index management and reducing errors.",
"authors": [
"vaeng"
]
}
94 changes: 94 additions & 0 deletions concepts/ranged-loops/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Introduction

When working with arrays or vectors in C++, iterating over their elements is a common task.
A range-based `for` loop provides a concise and readable way to access the elements without dealing with indices.

## Basic Syntax

A range-based `for` loop consists of the following parts:

```cpp
for (element_type temp_element : container) {
// Use temp_element inside the loop
}
```

- `element_type`: The type of each element in the container.
- `temp_element`: A temporary variable that holds the value of each element.
- `container`: The array or vector to loop over.

## Example Usage

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This took me a minute to work out but I like it! :)

Maybe it would be worth saying...

Suggested change
In this code, we loop over each word, retrieving the first letter each time, to reveal the obscured password.

```cpp
#include <vector>
#include <iostream>

std::vector<std::string> obscured_password {"Tooms", "roswell", "uFO", "scully", "tunguska", "Nicholas Lea", "oil", "1Breath"};
for (std::string part : obscured_password) {
part = part.substr(0,1);
std::cout << part;
}
// Output: TrustNo1
```

The ranged loop syntax eliminates the need for manual indexing, making the code cleaner and less error-prone.
Other languages reference to a similar access style as `for each` loop.

The example above shows access by value.
Although the `part` variable is changed inside the loop, the original vector remains unchanged.
This means each element of the container will be a copied and assigned to the part variable - that may in turn impact performance.

## Using `const` for Read-Only Access

If you do not need to modify the elements, using `const` ensures they remain unchanged:

```cpp
std::vector<std::string> file_name {"Jraphics", "Interchange", "Format"};
for (const std::string part : file_name) {
std::cout << part.front();
}
// Output: JIF
```

This prevents accidental modification of `part` but will still make a copy with every side-effect from above.

## Using References to Modify Elements

With a reference (`&`) you can modify the original container and avoid copies:

Range-based `for` loops also work with arrays:

```cpp
#include <array>

std::array<std::string, 3> trilobites {"Johnny", "Joey", "Dee Dee", "CJ"};

for (std::string& member : trilobites) {
member += " Ramone";
}
// trilobites now contains "Johnny Ramone", "Joey Ramone", "Dee Dee Ramone", "CJ Ramone"};
```

~~~~exercism/note
If you don't change your loop variable, it is advisable to use `const` references.
Copy operations can significantly slow your algorithms for larger data structures.
The only exception for this rule are [fundamental types][fundamentals] like `int`, `char`, and `long`, as the reference process has more overhead than a simple copy.

[fudnamentals]: https://en.cppreference.com/w/cpp/language/types
~~~~

## When to Use Range-Based Loops

- When you need to read or modify each element in a container.
- When you do not need to track indices explicitly.
- When you want clearer, more maintainable code.

## Limitations

- You cannot modify the structure of a container (e.g., adding or removing elements) while iterating.
- You cannot access the index of an element directly.

~~~~exercism/note
As the elements are always traversed in order and never skipped, you can build your own counter to get an index.
If you really need the index of an element, a traditional `for` loop might be a better choice.
~~~~
10 changes: 10 additions & 0 deletions concepts/ranged-loops/links.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[
{
"url": "https://en.cppreference.com/w/cpp/language/range-for",
"description": "C++ reference on ranged for loops"
},
{
"url": "https://www.learncpp.com/cpp-tutorial/range-based-for-loops-for-each/",
"description": "Range-based for loops (for-each) chapter on Learn C++"
}
]
5 changes: 5 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -1350,6 +1350,11 @@
"uuid": "5de475cc-5321-476f-bd19-a82b60284f5a",
"slug": "literals",
"name": "Literals"
},
{
"uuid": "6ae189b1-2195-4514-abb5-bd270ba5b7c4",
"slug": "ranged-loops",
"name": "Range-based For Loops"
}
],
"key_features": [