我有一个这样的用户定义结构:
struct Cell{
int dirty;
double data;
Cell* c;
// bool operator==(const struct Cell& other) {
// /* I am not sure if I need this function here...*/
// }
};
然后,我定义了一个这样的列表:
list<Cell> cell_list;
我要做的是删除“cell_list”中满足条件的所有元素
(certain_cell.dirty == 1)
谁能告诉我如何有效地实现上述操作?
最佳答案
在没有 lambda 的情况下(即 C++11 之前的版本):
#include <iostream>
#include <list>
struct Cell {
bool dirty;
Cell(bool dirt=false) : dirty(dirt) { }
};
typedef std::list<Cell> CellList;
bool isDirty(const Cell& c) {
return c.dirty;
}
int main() {
CellList cells;
cells.push_back(Cell());
cells.push_back(Cell());
cells.push_back(Cell(true));
cells.push_back(Cell());
cells.push_back(Cell(true));
for (CellList::const_iterator i=cells.begin(); i!=cells.end(); ++i)
std::cout << i->dirty << '\n';
std::cout << '\n';
cells.remove_if( isDirty );
for (CellList::const_iterator i=cells.begin(); i!=cells.end(); ++i)
std::cout << i->dirty << '\n';
std::cout << '\n';
}
关于c++ - 删除 std :list<User_Define> that satisfy certain conditions? 中元素的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507766/