EasyHack Suggestion: Use range based for loops
hossein at libreoffice.org
Thu Oct 21 13:53:45 UTC 2021
This is a suggestion for adding an EasyHack with the difficulty
"Beginner". I have asked one of the newbies to do a submission regarding
this. Please tell me your opinion. I welcome any suggestions.
**Use range based for loops**
Since C++11, range based loops are available for iterating over a known
range of values. For example, when there is a need to process elements
of a container, range based loops are usually a good choice. They are
easy to write, read and understand.
The simplest form is as below:
for(auto variable : range)
In this way, a temporary variable is created to iterate over the range
of values. But this is usually undesirable because the variable is
When a change in the values of the elements is needed, a reference is
for(auto &variable : range)
It is possible to use the reference, but use const to prevent
modification. This is useful for working on big elements.
for(const auto &variable : range)
Range based loops can simplify the code, but there are limitations for
them. For example, if there is a need not to iterate over certain
values, std::ranges::views::drop (C++20) should be used, so they are not
suitable for replacing every normal for loop.
This is an example:
123758: Use range based for loops |
This is changed:
for(size_t a(0); a < aMatrices.size(); a++)
getTransformation() * aMatrices[a],
for(const auto &a : aMatrices)
getTransformation() * a, Primitive2DContainer(xSeq)));
+ Range-based for loop
+Range-based for Statement (C++)
Hossein Nourikhah, Ph.D.
Developer Community Architect
The Document Foundation (TDF)
Email: hossein at libreoffice.org
IRC: hossein at libreoffice-dev room in LiberaChat Network
More information about the LibreOffice