简体   繁体   English

如何跳过基于范围的 for 循环的第一次迭代?

[英]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?如何跳过colourPos向量的第一次迭代?

Can I use .begin() and .end() ?我可以使用.begin().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:C++20 开始,您可以使用Ranges 库中的范围适配器std::views::drop以及基于范围的 for 循环来跳过第一个元素,如下所示:

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

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

Output:输出:

Pos = 2位置 = 2
Pos = 3位置 = 3

Code on Wandbox 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.注意:我不建议使用包含begin()和/或end()的解决方案,因为基于范围的 for 循环的想法是摆脱迭代器。 If you need iterators, then I would stick with an interator-based for loop.如果您需要迭代器,那么我会坚持使用基于迭代器的 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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