std::remove_if用法学习

转自:https://blog.csdn.net/KFLING/article/details/80187847,

1.介绍

#include  <algorithm>  //头文件
remove_if(begin,end,op);//(迭代器-开始位置,迭代器-终止位置,回调函数)

如果回调函数返回为真,则将当前所指向的参数移到尾部,返回值是被移动区域的首个元素。

由于remove_if函数的参数是迭代器,通过迭代器无法得到容器本身,而要删除容器内的元素必须通过容器的成员函数来进行。 remove_if只能把要删除的元素移到容器末尾并返回要被删除元素的迭代器,然后通过erase成员函数来真正删除。因此一般remove_if和erase函数是成对出现的。

remove_if的函数原型如下:

template<class ForwardIt, class UnaryPredicate>
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
    first = std::find_if(first, last, p); //找到符合条件的元素所在的位置
    if (first != last)
        for(ForwardIt i = first; ++i != last; )
            if (!p(*i))//将不符合条件的往前移动
                *first++ = std::move(*i);// 先*first,将*i的值覆盖掉first指向的内容,first++往后移动
    return first;
}

//最后first和end之间的元素就是符合条件p的,并且已经被覆盖掉了,选择用erase删除。

例子:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
bool isSpace(char x) { return x == ' '; }//返回类型为bool
 
int main()
{
    string s2("Text with    spaces");
    cout << "删除之前"<<s2 << endl;
    s2.erase(remove_if(s2.begin(), s2.end(), isSpace), s2.end());
    cout <<"删除之后"<< s2 << endl;
    return 0;
}

输出:
删除之前Text with    spaces
删除之后Textwithspaces

 unordered_set不能使用remove_if,关联容器好像都不能使用。可以使用erase_if,但是是从c++20开始有的。

std::unordered_set 类型不直接支持 remove_if 函数。remove_if 函数通常与序列容器(如 std::vector、std::list)一起使用,因为它们支持连续存储的元素,可以通过移动元素来实现删除操作。

 然而,你可以使用 std::erase_if 算法(C++20 新增)来从 std::unordered_set 中删除满足特定条件的元素。std::erase_if 会在 C++20 的 <algorithm> 头文件中定义。

posted @ 2023-12-26 15:33  lypbendlf  阅读(368)  评论(0编辑  收藏  举报