2014-09-03 199 views
5
for (int p : colourPos[i+1]) 

如何跳過我的colourPos向量的第一次迭代?跳過第一次基於範圍的迭代循環

我可以使用.beginend

+0

'布爾第一= TRUE; for(int p:colourPos){if(first){first = false;繼續;如果(first == 1){first = 0;}; // ...代碼在這裏}' – NetVipeC 2014-09-03 19:48:37

+0

'first = 1;'then'繼續; }'? – 2014-09-03 19:48:42

+1

也許你更喜歡使用'std :: for_each'而不是基於範圍的循環? – YoungJohn 2014-09-03 19:50:59

回答

7

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 << " "; 
    } 
} 

輸出:

2 3 4 

或者簡單:

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 << " "; 
    } 
} 

輸出:

2 3 4 
7

這樣做:

bool first = true; 

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

    // ... 
}