0

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

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)

谁能给我一些关于如何有效实现上述操作的指导?

4

3 回答 3

2

要做到这一点,无需 lambdas(即 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';
}
于 2015-07-20T02:13:29.980 回答
2

list实际上有一个名为的成员函数remove_if

cell_list.remove_if([](const Cell& cell){
    return cell.dirty == 1;
});
于 2015-07-20T01:46:09.547 回答
0

这可以用于所有容器,但对于连续容器(例如vector. 如果您想处理所有内容并一次性删除列表中的某些元素,这尤其会派上用场。

list<Cell> cells;
list<Cell>::iterator itr = cells.begin();
while( itr != cells.end() )
{
    if( itr->dirty == 1 )
        itr = cells.erase(itr);
    else
        ++itr;
}
于 2015-07-20T02:18:54.877 回答