如何根据元素的某些属性删除 std::vector 的元素?

发布于 2024-07-15 05:54:10 字数 144 浏览 4 评论 0原文

例如,如果您有一个 std::vector,其中 MyClass 有一个公共方法:bool isTiredOfLife(),您如何删除返回 true 的元素?

If for instance you have a std::vector<MyClass>, where MyClass has a public method: bool isTiredOfLife(), how do you remove the elements that return true?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终陌 2024-07-22 05:54:10

我更喜欢remove_if

v.erase(remove_if(v.begin(), v.end(), 
                 mem_fun_ref(&MyClass::isTiredOfLife)), 
        v.end());

remove_if 返回一个指向后面的迭代器仍在序列中的最后一个元素。 erase 删除从第一个参数到最后一个参数(两个迭代器)的所有内容。

I prefer remove_if

v.erase(remove_if(v.begin(), v.end(), 
                 mem_fun_ref(&MyClass::isTiredOfLife)), 
        v.end());

remove_if returns an iterator pointing after the last element that's still in the sequence. erase erases everything from its first to its last argument (both iterators).

白馒头 2024-07-22 05:54:10

使用remove_if是执行此操作的“正确”方法。 请注意不要使用迭代器来循环和擦除,因为删除项目会使迭代器失效。 事实上,任何使用擦除()作为其主要方法的示例对于向量来说都是一个坏主意,因为擦除的时间复杂度为 O(n),这将使您的算法为 O(n^2)。 这应该是一个 O(n) 算法。

我下面给出的方法可能比remove_if更快,但与remove_if不同,它不会保留元素的相对顺序。 如果您关心维护顺序(即您的向量已排序),请使用remove_if,如上面的答案所示。 如果您不关心顺序,并且要删除的项目数通常小于向量的四分之一,则此方法可能会更快:

for( size_t i = 0; i < vec.size(); )
   if( vec[i].isTiredOfLife() )
   {
      vec[i] = vec.back();
      vec.pop_back();
   }
   else
      ++i;

Using remove_if is the "right" way to do this. Be careful NOT to use an iterator to cycle through and erase, because removing items invalidates the iterator. In fact, any example which uses erase() as its primary method is a bad idea on vectors, because erase is O(n), which will make your algorithm O(n^2). This should be an O(n) algorithm.

The method I give below is likely to be faster than remove_if but, unlike remove_if, will NOT preserve the relative order of the elements. If you care about maintaining order (i.e. your vector is sorted), use remove_if, as in the answer above. If you don't care about order, and if the number of items to be deleted is typically less than a quarter of the vector, this method is likely to be faster:

for( size_t i = 0; i < vec.size(); )
   if( vec[i].isTiredOfLife() )
   {
      vec[i] = vec.back();
      vec.pop_back();
   }
   else
      ++i;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文