-
-
Notifications
You must be signed in to change notification settings - Fork 229
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
vaeng
wants to merge
4
commits into
main
Choose a base branch
from
add-range-based-loop-concept
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+115
−0
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2ef5af7
docs: add ranged based for loop concept files
vaeng f5ab895
fixup! docs: add ranged based for loop concept files
vaeng 372f5e1
fixup! fixup! docs: add ranged based for loop concept files
vaeng c2fcc72
fixup! fixup! fixup! docs: add ranged based for loop concept files
vaeng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
```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. | ||
~~~~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++" | ||
} | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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...