25
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

std::remove_ifは実際には要素の削除を行わない。

Posted at

std::remove_ifは条件を満たす(述語が真を返す)要素を実際削除するわけではなく、「削除する要素を詰めて、サイズが縮んだコンテナの新しい終端イテレータを返す」だけなので、その後の要素の削除は自分でやらないといけません。

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
std::vector<int> v = {1,2,3,4,5,6,7};

// "1 2 3 4 5 6 7"
for(auto i=v.begin();i!=v.end();++i)
  {std::cout << *i << " ";}
std::cout << std::endl;

auto itrNewEnd = std::remove_if(v.begin(),v.end()
                                ,[](int i)->bool
                                 { return 3<=i&&i<=5; });

v.erase(itrNewEnd,v.end());

// "1 2 6 7"
// 上記のv.erase()をコメントアウトすると "1 2 6 7 5 6 7"
for(auto i=v.begin();i!=v.end();++i)
  {std::cout << *i << " ";}
std::cout << std::endl;

return 0;
}
25
26
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?