通过包裹环绕的C 向量迭代



我有一个通过向量迭代的分配,并删除每个第三个数字。如果它撞到向量的末端,则应从第一个条目开始继续计数,直到仅保留一个数字为止。用户输入向量中应有多少个数字。

我很难习惯向量和数组之间的区别 - 就在上周,我们遇到了一个问题,涉及在数组中包裹的问题,该数组已通过mod解决,但我很快发现这对向量不起作用。

到目前

 while (vector.size > 1) {
            for(std::vector<int>::iterator i = suitors.begin(); i <= suitors.end(); i++) {
           // here, add a case for if it hits the end, start over
           if (i = suitors.end()) {
                   i = suitors.begin();
           }
           suitors.erase(suitors.at(i) + 2);
    }

我遇到的问题是弄清楚如何重新开始,因为当我尝试以这种方式使用i时出现错误。

有什么建议或提示让我走上正确的道路?我开始看到多功能矢量的多样性,但是它们还没有点击。我也不确定是否有更好的方法可以阻止它以外的循环。

我会使用remove_if将矢量中的项目移动到每次索引变量时,每次达到3。

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
  std::vector<int> v{1,2,3,4,5,6};
  unsigned index = 0;   // this is the index variable used to remove elements
  auto end = v.end();   // point to the current end of the vector
  // keep looping until there is only 1 element in the vector
  while(std::distance(v.begin(), end) > 1) {
    // remove_if will call the predicate for each element
    // the predicate simply increments the index each time, and when it reaches 
    // 3 indicates that element should be removed
    // remove_if will move items to the end of the vector and return an 
    // iterator to the end of the new range, so we'll update the end variable 
    // with the result
    end = std::remove_if(v.begin(), end, [&index](int) {
      if(++index == 3) {
        // reset the index and indicate this element should be removed
        return (index = 0), true;
      }
      return false;
    });
    for(auto iter = v.begin(); iter != end; ++iter) {
      std::cout << *iter << ' ';
    }
    std::cout << 'n';
  }
  // erase all the elements we've removed so far
  v.erase(end, v.end());
}

输出:

1 2 4 5 
1 2 5 
1 5 
1

实时演示

我假设只要向量具有多个元素,我假设的循环意味着要走,但这应该包含在for中,而不是另一个循环

句法问题在IF中:

if (i = suitors.end())
   // ^ should be ==

否则,您只是将终点分配给迭代器

for(std::vector<int>::iterator i = suitors.begin(); suitors.size() > 1; ++i) {
                                                 // ^ loop condition changed
       if (i == suitors.end()) {
           i = suitors.begin();
       }
       suitors.erase(suitors.at(i) + 2);
}

在您迭代其迭代时修改容器很危险。

最新更新