Hello,
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.
Regards,
Hossein
--------------------
**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)
statement;
In this way, a temporary variable is created to iterate over the range
of values. But this is usually undesirable because the variable is
copied.
When a change in the values of the elements is needed, a reference is
used:
for(auto &variable : range)
statement;
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)
statement;
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 |
https://gerrit.libreoffice.org/c/core/+/123758
This is changed:
for(size_t a(0); a < aMatrices.size(); a++)
{
rContainer.push_back(new TransformPrimitive2D(
getTransformation() * aMatrices[a],
Primitive2DContainer(xSeq)));
}
into this:
for(const auto &a : aMatrices)
{
rContainer.push_back(new TransformPrimitive2D(
getTransformation() * a, Primitive2DContainer(xSeq)));
}
References:
+ Range-based for loop
https://en.cppreference.com/w/cpp/language/range-for
+Range-based for Statement (C++)
https://docs.microsoft.com/en-us/cpp/cpp/range-based-for-statement-cpp
--------------------
--
Hossein Nourikhah, Ph.D.
Developer Community Architect
The Document Foundation (TDF)
Email: hossein@xxxxxxxxxxxxxxx
Wiki: https://wiki.documentfoundation.org/User:Hossein
IRC: hossein at libreoffice-dev room in LiberaChat Network
irc://irc.libera.chat/#libreoffice-dev