简体   繁体   English

如何在 C++ 中迭代矢量时擦除或更改元素?

[英]How to erase or change element while iterating over vector in C++?

I was in the middle of creating a simple sieve of Erathostenes function when I stumbled upon one obstacle.当我偶然发现一个障碍时,我正在创建一个简单的 Erathostenes function 筛子。 In to order to accomplish the highest efficiency in this task I wanted to use only a vector.为了完成这项任务的最高效率,我只想使用一个向量。 Here is the current code:这是当前代码:

vector<int> sieveOfErathostenes(int N) {

        vector <int> result(N, 1);

        for(int i = 2; i < sqrt(N); i++)

                if(result[i] == 1)

                        for(int j = 2*i; j < N; j += i)

                                result.at(j) = 0;
        //  :c
        return result;
}

This vector returns 1 and 0 in the proper position but I can't figure out how to implement both erasing or changing an element's value in a single loop.该向量在正确的 position 中返回 1 和 0,但我无法弄清楚如何在单个循环中实现擦除或更改元素的值。 When I use an iterator to erase an element as in erase set element while iterating/// I can't access the vector to change its value, and when I use a standard for loop to access the element I can't remove it.当我在迭代时使用迭代器擦除元素时,就像在擦除集合元素中一样///我无法访问向量来更改其值,并且当我使用标准 for 循环访问元素时,我无法删除它。 I have tried going from the end of the vector and counting non zero elements and giving some offset when erasing but no success.我尝试从向量的末尾开始计算非零元素并在擦除时给出一些偏移但没有成功。 TL DR: What I can't figure out is: TL DR:我想不通的是:

for(int i = 0; i < N; i++)
{
        if(result[i] == 0) {
                //remove at position i
        } else {
                result.at(i) = i;
        }
}

Thank you in advance for your time:)提前感谢您的时间:)

Instead of erasing elements in the middle of the vector, you should write the results from the beginning of the vector and eliminate the unused elements in the end of vector.与其擦除向量中间的元素,不如从向量的开头写入结果,并消除向量末尾未使用的元素。

int finalSize = 0;
for(int i = 0; i < N; i++)
{
        if(result[i] != 0) {
                result[finalSize++] = i;
        }
}
result.resize(finalSize);

If you still need to remove an element from a std::vector during traversal, keep in mind that erase returns an iterator following the last removed element:如果在遍历期间仍需要从std::vector中删除元素,请记住, erase在最后一个删除的元素之后返回一个迭代器:

  std::vector<int> result = {1,1,1,0,1,1,1};
  for(auto it = result.begin(); it != result.end(); )
  {
    if(*it==0)
      it = result.erase(it);
    else
      it++;
  }

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

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