Skip 1st Iteration of Range-Based For Loops [dupli

2019-02-09 18:11发布

问题:

This question already has an answer here:

  • Skipping in Range-based for based on 'index'? 7 answers
for (int p : colourPos[i+1])

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

Can I use .begin and end?

回答1:

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


回答2:

Do this:

bool first = true;

for (int p : colourPos)
{
    if (first)
    { first = false; continue; }

    // ...
}