0
点赞
收藏
分享

微信扫一扫

remove_if的使用

remove_if(iterator1, iterator2, func());

用于对容器内的元素进行操作,源码如下:

template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
                             UnaryPredicate pred)
{
  ForwardIterator result = first;
  while (first!=last) {
    if (!pred(*first)) {
      *result = std::move(*first);
      ++result;
    }
    ++first;
  }
  return result;
}

特性:只是在符合删除条件的元素本来的位置上用后来的元素进行了替换,并不会删除多余的空间,执行完毕后,返回剩余元素下一位的迭代器。

要想在remove以后,删除多余的元素,需要在remove_if的外层使用erase函数,例子如下:

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
    std::vector<string> c { "123", "4564", "426567", "543d5", "4" };
    int x = 4;
    c.erase(std::remove_if(c.begin(), c.end(), [x](string n) { return n.size() >= 4; } ), c.end());
    std::cout << "c: ";
    for (auto i: c) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
}


举报

相关推荐

0 条评论