2015-07-20 57 views
0

我有一个用户定义的结构是这样的:删除std:list <User_Define>中满足特定条件的元素的最佳方法是什么?

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) 

可能有人给我如何有效地实现上述操作的某些指令的条件?

+0

使用'remove_if'。像'cell_list.remove_if([](Cell&c){return c.dirty;});'和'dirty'应该可能是'bool'。 – ooga

+1

@ooga答案属于答案。 – Barry

+0

@Barry这是一个微不足道的问题,我想我会给OP一个删除它的机会。 – ooga

回答

2

要做到这一点而不的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'; 
} 
+0

我可以建议'remove_if(&isDirty);'代替可读性。只是'isDirty'看起来你忘了调用这个函数。 – sp2danny

2

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

cell_list.remove_if([](const Cell& cell){ 
    return cell.dirty == 1; 
}); 
+0

谢谢您的快速回复,先生!但是,当我编译它。我得到这样的错误:“警告:lambda表达式仅适用于-std = C++ 11或-std = gnu ++ 11”和“错误:没有匹配函数调用'std :: list :: remove_if MyClass :: myfunction(int *,int):: __ lambda0)'cell_list.remove_if([](const Cell&c){return(c.dirty == 1);});“我知道也许我用” -std = C++ 11“可以解决这个问题,但是有没有其他解决这个编译错误的方法? (我不想使用C++ 11,因为我将把我的代码集成到别人的代码中,而这些代码不是用C++ 11编译的) –

+1

保持与C++ 03兼容的原因很少。它不仅是12岁,它也是以前的标准。 C++ 11没有太多的兼容性问题,升级通常很轻松。 – sp2danny

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; 
} 
+0

有算法可以更好地做到这一点。像这样编写一个原始循环效率低下且容易出错。 – Barry

相关问题