How to make a for loop variable const with the exception of the increment statement?

后端 未结 9 1229
天涯浪人
天涯浪人 2020-12-24 04:26

Consider a standard for loop:

for (int i = 0; i < 10; ++i) 
{
   // do something with i
}

I want to prevent the variable i fr

9条回答
  •  长情又很酷
    2020-12-24 05:06

    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)

提交回复
热议问题