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执行完后,内存中为

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

2158

被折叠的 条评论
为什么被折叠?



