std::remove_if - lambda,不从集合中删除任何内容

2023-12-19

好吧,我想我在这里犯了一个愚蠢的错误。我有一个 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 个在其模式集合中具有任何 DisplayMode3d,但列表中没有删除任何内容。

我在这里犯了什么愚蠢的错误?

Edit:

好吧,我的错误是我应该使用 MyDisplayDevices.remove_if 而不是 std::remove_if,但是下面的答案对于使用 std::remove_if :p 是正确的。

MyDisplayDevices.remove_if( [](DisplayDevice3d const & device) 
                            { 
                                return device.Modes.size() == 0; 
                            });

您需要对从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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::remove_if - lambda,不从集合中删除任何内容 的相关文章

随机推荐