C++程序员应了解的那些事(34)remove_if(begin,end,op)

参数说明:
remove_if(begin,end,op);  
前两个参数是迭代器,表示迭代的起始位置和停止位置;
最后一个参数:传入一个回调函数,如果回调函数返回为真,则将当前所指向的参数移到尾部。
※返回值是被移动区域的首个元素※

        remove_if在头文件algorithm中,故要使用此函数,需添加#include <algorithm>

        由于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);
    return first;
}
<示例1>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
bool isSpace(char x) { return x == ' '; }
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
<示例2>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
int main()
{
	vector<string> str = { "apple", "banana", "key", "cat", "dog", "orange", "banana" };
	auto find_str = "banana";
	str.erase(remove_if(str.begin(), str.end(),[find_str](string n) { return n == find_str; }),str.end());
	for (auto iter = str.begin(); iter != str.end(); ++iter)
	{
		cout << "删除之后:"<<*iter<<" ";
	}
	return 0;
}
输出:
apple key cat dog orange

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值