Rob*_*son 43 c++ lambda erase-remove-idiom remove-if c++11
好吧,我希望我在这里犯了一个愚蠢的错误.我有一个DisplayDevice3d列表,每个DisplayDevice3d都包含一个DisplayMode3d列表.我想删除DisplayDevice3d列表中没有任何DisplayMode3d的所有项目.我正在尝试使用Lambda来做它,即:
// If the device doesn't have any modes, remove it.
std::remove_if(MyDisplayDevices.begin(), MyDisplayDevices.end(),
[](DisplayDevice3d& device)
{
return device.Modes.size() == 0;
}
);
Run Code Online (Sandbox Code Playgroud)
即使出6名DisplayMode3d在MyDisplayDevices,只有1个有什么DisplayMode3d的其模式集合中,没有被从列表中删除.
我在这里犯了什么错误?
编辑:
好吧,我的错误是我应该使用MyDisplayDevices.remove_if而不是std :: remove_if,但是下面的答案对于使用std :: remove_if:p是正确的.
MyDisplayDevices.remove_if( [](DisplayDevice3d const & device)
{
return device.Modes.size() == 0;
});
Run Code Online (Sandbox Code Playgroud)
小智 72
你需要在从remove_if返回的迭代器上调用erase,它应该是这样的:
auto new_end = std::remove_if(MyDisplayDevices.begin(), MyDisplayDevices.end(),
[](const DisplayDevice3d& device)
{ return device.Modes.size() == 0; });
MyDisplayDevices.erase(new_end, MyDisplayDevices.end());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34796 次 |
| 最近记录: |