Search code examples
c++listvectorstdlistremove-if

What is the best way to remove elements in a std:list<User_Define> that satisfy certain conditions?


I have a user-defined structure like this:

struct Cell{
   int dirty;
   double data;
   Cell* c;
 //  bool operator==(const struct Cell& other) {
 //   /* I am not sure if I need this function here...*/
 //  }
};

Then, I defined a list like this:

list<Cell> cell_list;

What I want to do is to delete any elements in "cell_list" that satisfy the condition

(certain_cell.dirty == 1)

Could anybody give me some instructions on how to effectively realize the above operations?


Solution

  • To do it without lambdas (i.e., pre-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';
    }