参数说明:
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