Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c++ - How can I skip the first iteration of range-based for loops?

I would like to do something like this:

for (int p : colourPos[i+1])

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

Can I use .begin() and .end()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...