Consider a standard for loop:
for (int i = 0; i < 10; ++i)
{
// do something with i
}
I want to prevent the variable i fr
If you do not have access to c++20, typical makeover using a function
#include
#include // std::iota
std::vector makeRange(const int start, const int end) noexcept
{
std::vector vecRange(end - start);
std::iota(vecRange.begin(), vecRange.end(), start);
return vecRange;
}
now you could
for (const int i : makeRange(0, 10))
{
std::cout << i << " "; // ok
//i = 100; // error
}
(See a Demo)
Update: Inspired from the @Human-Compiler's comment, I was wondering weather the given answers have any difference in the case of performance. It turn out that, except for this approach, for all other approaches surprisingly have same performance (for the range [0, 10)). The std::vector approach is the worst.
(See Online Quick-Bench)