如何使用擦除删除成语从struct的向量中擦除值?

dja*_*ooo 0 c++ struct vector erase-remove-idiom

如何从struct的vector中删除所有值,其中struct value k等于0?

struct tabuRecord {
int x;
int y;
int k;
tabuRecord( int x, int y, int k)
    : x(x), y(y), k(k){}
};  

vector <tabuRecord> tabu;

v.insert(v.begin(), tabuRecord(1, 2, 3));
v.insert(v.begin(), tabuRecord(4, 5, 0));
v.insert(v.begin(), tabuRecord(7, 8, 9));
v.insert(v.begin(), tabuRecord(10, 11, 0));
Run Code Online (Sandbox Code Playgroud)

我试过了

tabu.erase(std::remove(tabu.begin(), tabu.end(), tabu.k=0), tabu.end());
Run Code Online (Sandbox Code Playgroud)

和

tabu.erase(std::remove(tabu.begin(), tabu.end(), tabuRecord.k=0), tabu.end());
Run Code Online (Sandbox Code Playgroud)

Mat*_*her 6

我想你要做的是删除所有的对象k==0,所以为此创建一个lambda:

tabu.erase(
    std::remove_if(tabu.begin(), tabu.end(),[](const tabuRecord& t){return t.k == 0;}),
    tabu.end());
Run Code Online (Sandbox Code Playgroud)

std::remove无法工作,因为它不是你想要删除的一个值,而是具有特定模式的所有值,这是什么std::remove_if.