diff --git a/concepts/ranged-loops/.meta/config.json b/concepts/ranged-loops/.meta/config.json new file mode 100644 index 00000000..c4f05eeb --- /dev/null +++ b/concepts/ranged-loops/.meta/config.json @@ -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" + ] +} diff --git a/concepts/ranged-loops/introduction.md b/concepts/ranged-loops/introduction.md new file mode 100644 index 00000000..0242a215 --- /dev/null +++ b/concepts/ranged-loops/introduction.md @@ -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 +#include + +std::vector 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 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 + +std::array 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. +~~~~ diff --git a/concepts/ranged-loops/links.json b/concepts/ranged-loops/links.json new file mode 100644 index 00000000..31853ad0 --- /dev/null +++ b/concepts/ranged-loops/links.json @@ -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++" + } +] \ No newline at end of file diff --git a/config.json b/config.json index aff67381..4d30d3fa 100644 --- a/config.json +++ b/config.json @@ -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": [