简体   繁体   中英

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() ?

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

Do this:

bool first = true;

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

    // ...
}

Since C++20 you can use the range adaptor std::views::drop from the Ranges library together with a range-based for loop for skipping the first element, as follows:

std::vector<int> colourPos { 1, 2, 3 };

for (int p : colourPos | std::views::drop(1)) {
    std::cout << "Pos = " << p << std::endl;
}

Output:

Pos = 2
Pos = 3

Code on Wandbox

Note: I would not recommend using a solution that contains begin() and/or end() , because the idea of a range-based for loop is to get rid of iterators. If you need iterators, then I would stick with an interator-based for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM