Skip 1st Iteration of Range-Based For Loops

前端 未结 2 1661
深忆病人
深忆病人 2020-12-16 01:16
for (int p : colourPos[i+1])

How do I skip the first iteration of my colourPos vector?

Can I use .begin and

相关标签:
2条回答
  • 2020-12-16 01:38

    Live demo link.

    #include <iostream>
    #include <vector>
    #include <iterator>
    #include <cstddef>
    
    template <typename T>
    struct skip
    {
        T& t;
        std::size_t n;
        skip(T& v, std::size_t s) : t(v), n(s) {}
        auto begin() -> decltype(std::begin(t))
        {
            return std::next(std::begin(t), n);
        }
        auto end() -> decltype(std::end(t))
        {
            return std::end(t);
        }
    };
    
    int main()
    {
        std::vector<int> v{ 1, 2, 3, 4 };
    
        for (auto p : skip<decltype(v)>(v, 1))
        {
            std::cout << p << " ";
        }
    }
    

    Output:

    2 3 4
    

    Or simpler:

    Yet another live demo link.

    #include <iostream>
    #include <vector>
    
    template <typename T>
    struct range_t
    {
        T b, e;
        range_t(T x, T y) : b(x), e(y) {}
        T begin()
        {
            return b;
        }
        T end()
        {
            return e;
        }
    };
    
    template <typename T>
    range_t<T> range(T b, T e)
    {
        return range_t<T>(b, e);
    }
    
    int main()
    {
        std::vector<int> v{ 1, 2, 3, 4 };
    
        for (auto p : range(v.begin()+1, v.end()))
        {
            std::cout << p << " ";
        }
    }
    

    Output:

    2 3 4
    
    0 讨论(0)
  • 2020-12-16 01:51

    Do this:

    bool first = true;
    
    for (int p : colourPos)
    {
        if (first)
        { first = false; continue; }
    
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题