【发布时间】:2011-05-27 14:10:51
【问题描述】:
好吧,我想我在这里犯了一个愚蠢的错误。我有一个 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;
}
);
即使在 MyDisplayDevices 中的 6 个 DisplayMode3d 中,只有 1 个在其 Modes 集合中有任何 DisplayMode3d,但没有从列表中删除任何内容。
我在这里犯了什么重大错误?
编辑:
好吧,我的错误是我应该使用 MyDisplayDevices.remove_if 而不是 std::remove_if,但是下面的答案对于使用 std::remove_if 是正确的:p。
MyDisplayDevices.remove_if( [](DisplayDevice3d const & device)
{
return device.Modes.size() == 0;
});
【问题讨论】:
-
如果容器本身支持remove_if,那么一定要使用它。我相信 std::list 就是这种情况。对于不提供 remove_if 的容器,您可以将 std::remove_if 与容器的擦除成员函数结合使用。
-
@sellibitze 换句话说,老鼠药
标签: c++ c++11 lambda remove-if erase-remove-idiom