gpt4 book ai didi

c++ - 删除 std :list that satisfy certain conditions? 中元素的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-27 22:57:21 24 4
gpt4 key购买 nike

我有一个这样的用户定义结构:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com