到达终点后返回Vector的顶部c ++

时间:2019-03-08 10:45:19

标签: c++ vector

我目前有一个迭代器,该迭代器可在向量中随机递增,我希望一旦到达终点,便可以返回到向量的顶部。我在随机生成器中放置了一个种子,所以我有相同的序列。显然,此刻向量超出了范围

int main() 
{
vector<int> vectorTest = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 
10, 11, 12, 13, 14, 15, 16,
    17, 18, 19, 20};  

vector <int>::iterator it;

for (it = vectorTest.begin(); it != vectorTest.end(); it = it + rand() % 6)
{ 
    cout << *it << endl;    
}
}

2 个答案:

答案 0 :(得分:1)

这不是迭代器的用例。我建议使用以向量长度为​​模的边界的通用索引。

int j = 0;
for (int i = 0; j < 20 ; i = (i + rand() % 6) % vectorTest.size(), j++) {
    cout << vectorTest[i] << endl;
}

答案 1 :(得分:1)

您可以使用ranges::view::cycle无限期地重复矢量元素。

int main() 
{
    std::vector<int> vectorTest = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};  

    auto repeating = vectorTest | ranges::view::cycle;

    for (auto it = repeating.begin(); /* how to end? */; it = it + rand() % 6)
    { 
        std::cout << *it << std::endl;    
    }
}