Iterating over an odd (even) elements only in a range-based loop

前端 未结 4 1268
无人共我
无人共我 2021-02-15 16:23

Suppose we have a plain array (or other container which support range based loops):

const int N = 8;
int arr[N] = {0, 1, 2, 3, 4, 5, 6, 7};

Usi

4条回答
  •  迷失自我
    2021-02-15 17:00

    This isn't really an answer to the question, but—for what it is worth—whenever I run into a limitation of ranged-for, I look for a standard algorithm solution. Like...

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        int arr[] {0, 1, 2, 3, 4, 5, 6, 7};
        std::copy_if(
            std::begin(arr), std::end(arr),
            std::ostream_iterator(std::cout, "\n"),
            [is_odd_element = true](int n) mutable {
                return std::exchange(is_odd_element, not is_odd_element);
            });
    }
    

提交回复
热议问题