'refactor c++ auto loops to use begin, end, operator++
Is there any way to refactor this:
for (auto it: container) { ... }
Into what it actually represents:
for (auto it=container.begin(); it != container.end(); ++it) { ... }
Since under the hood this is what happens, I wonder if there's a way to translate the former style to the latter
#include <iostream>
struct SomeClass {
int x[5] = {1,2,3,4,5};
int *begin() { return x+1; }
int *end() { return x+4; }
};
int main(int argc, char **argv)
{
SomeClass c;
for (auto it: c) { std::cout << it << "\n"; }
return 0;
}
Solution 1:[1]
There is, you can do re-engineering like this in clang-tidy, by writing your own plug-in. https://devblogs.microsoft.com/cppblog/exploring-clang-tooling-part-1-extending-clang-tidy/
Be aware this is a chunk of work, and you will need a bit of a beast of a machine to compile on. Specifically one with a lot of RAM.
Solution 2:[2]
You can check https://en.cppreference.com/w/cpp/language/range-for to apply the transformation manually.
Cppinsight is a tool that can expand your code to the equivalent iterator based loop.
Note however, that cppinsight produces a representation of the code that is internal to the compiler. It is not necessarily code that you should write yourself. In particular, names with two leading underscores are reserved and may not be used.
#include <iostream>
struct SomeClass
{
int x[5] = {1, 2, 3, 4, 5};
inline int * begin()
{
return this->x + 1;
}
inline int * end()
{
return this->x + 4;
}
// inline constexpr SomeClass() noexcept = default;
};
int main(int argc, char ** argv)
{
SomeClass c = SomeClass();
{
SomeClass & __range1 = c;
int * __begin1 = __range1.begin();
int * __end1 = __range1.end();
for(; __begin1 != __end1; ++__begin1) {
int it = *__begin1;
std::operator<<(std::cout.operator<<(it), "\n");
}
}
return 0;
}
Solution 3:[3]
The start address of an array is the name of the array.
And end()
points to the next part of the last element in the array.
So, begin() {return x;}
and end() {return x+5;}
.
You can check this site:
https://www.cplusplus.com/reference/iterator/begin/
https://www.cplusplus.com/reference/iterator/end/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tiger4Hire |
Solution 2 | |
Solution 3 | Obsidian |