使用find_if清除向量中的所有偶数

Bha*_*wan -1 c++ stl

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
#include <iomanip>

using namespace std;

bool isEven(int n)
{ 
    return n%2 == 0;
}

int main()
{
    srand(time(NULL));

    vector<int> myVec;

    for(int i = 0; i < 20; i++)
    {
        myVec.push_back(rand() % 100);
    }   
    while(1)
    {   
          vector<int>::iterator q = std::find_if(myVec.begin(), myVec.end(), isEven);
          cout << *q << endl;
          if(q == myVec.end())
          {   
             myVec.erase(q);
             break;
          }   
          else
             myVec.erase(q);        
      }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码给出了分段错误.上面的代码是使用find_if和erase函数从向量中删除所有偶数

请帮忙.任何帮助将受到高度赞赏.

编辑:我已经编辑它以确保迭代器始终有效.

它仍然给出了分段错误.

Sto*_*ica 5

std::vector::erase使擦除点之前和之后的所有迭代器无效.您不能继续使用该迭代器,不能增加它,使用它来访问矢量,甚至可以将它与之比较end().

要使用的正确算法是std:remove_if.与名称不同,它只会将向量的所有偶数项"移动到后面",而不会使任何迭代器无效.它会将迭代器返回到此子范围的开头,然后您可以将其提供给适当的erase重载(接受一对迭代器的重载).

这在代码中被广泛使用,甚至被命名为"擦除删除成语".