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

前端 未结 4 1270
无人共我
无人共我 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:16

    There is a ready-made solution for this problem in the Range-v3. I think this can be useful if you don’t want to write your own implementation or need more flexibility (f.e. arbitrary stride)

    #include 
    
    void example()
    {
        int data[8] = {0, 1, 2, 3, 4, 5, 6, 7};
        for (auto i : ranges::view::stride(data, 2))
        {
            std::cout << i << std::endl;
        }
    }
    

    (copied from @hlt comment)

提交回复
热议问题