Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 744
mrmike Avatar asked Sep 03 '14 19:09

mrmike


People also ask

How do you skip the first row in iterator?

Call next() once to discard the first row.

How do you skip elements in a for loop?

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration only. In other words, the loop will not terminate immediately but it will continue on with the next iteration. This is in contrast with the break statement which will terminate the loop completely.

How do you skip one step in a for loop in Python?

You can use a continue statement in Python to skip over part of a loop when a condition is met. Then, the rest of a loop will continue running. You use continue statements within loops, usually after an if statement.


1 Answers

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
like image 141
Piotr Skotnicki Avatar answered Sep 28 '22 12:09

Piotr Skotnicki