跳过第一次基于范围的迭代循环
答
#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 << " ";
}
}
输出:
2 3 4
或者简单:
#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 << " ";
}
}
输出:
2 3 4
答
这样做:
bool first = true;
for (int p : colourPos)
{
if (first)
{ first = false; continue; }
// ...
}
'布尔第一= TRUE; for(int p:colourPos){if(first){first = false;继续;如果(first == 1){first = 0;}; // ...代码在这里}' – NetVipeC 2014-09-03 19:48:37
'first = 1;'then'继续; }'? – 2014-09-03 19:48:42
也许你更喜欢使用'std :: for_each'而不是基于范围的循环? – YoungJohn 2014-09-03 19:50:59