STL——remove_if

本文详细介绍了C++标准模板库中的remove_if函数,包括其用法、如何配合erase函数实现元素的有效删除,以及具体的示例代码。通过本文,读者可以了解remove_if函数的工作原理及其在实际应用中的注意事项。

remove_if

remove_if(beg, end, op)   //移除区间[beg,end)中每一个“令判断式:op(elem)获得true”的元素;

remove_if函数返回result迭代器,其指向的最后一个元素
remove_if需要配合对象的erase函数使用,才能删除满足条件的元素,否则,只改变原对象的内存排布,将符合条件的元素向前移动

remove(beg,end,const T& value)  //移除区间{beg,end)中每一个“与value相等”的元素;

源码

在这里插入图片描述
观察其源码,使用(__result)和 (__first)指向同一块内存,使用(__first)指向首地址,例如指向"Text with spaces",当(__first)指向w,++result执行完后,内存中为
Textwwith    spaces

示例代码

erase配合remove_if

#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

如果不使用erase,则remove_if(s2.begin(), s2.end(), isSpace);

删除之前Text with    spaces
删除之后Textwithspacespaces
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值