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

标签 c++ list vector stdlist remove-if

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

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/

相关文章:

c# - 将列表<int> 转换为列表<long>

list - 带 Scalaz 的 ZipList

c++ - 无法在 Mac 上访问 std vector 迭代器 _Ptr

c++ - 保持顺序的 vector 差异

c++ - 未找到 libstdc++-6.dll

c++ - 从 Eigen::Translation 构造 Eigen::Transform

c++ - #include inside 函数体不起作用 (CDT/Eclipse C++)

list - 插入键值对后增加搜索树中的值

matlab - 在 MATLAB 中,每次值从 1 变为 0 时如何查找向量中的索引?

c++ - C中有const吗?