Remove()函数:
remove(beg,end,const T& value) //移除区间{beg,end)中每一个“与value相等”的元素;
remove只是通过迭代器的指针向前移动来删除,将没有被删除的元素放在链表的前面,并返回一个指向新的超尾值的迭代器。由于remove()函数不是成员,因此不能调整链表的长度。remove()函数并不是真正的删除,要想真正删除元素则可以使用erase()或者resize()函数。
例如:
#include <iostream>
#include <algorithm> //std::remove
#include<string>
using namespace std;
int main()
{
string s = "1, 9, 5, 4, 2, 6, 5, 7";
//remove算法,除去使第三个参数的值为true的元素
//注意,不管是什么算法,是不可能对原容器的数量进行改变
s.erase(remove(s.begin(), s.end(), '5'), s.end());//1,9,,4,2,6,,7
cout << s << endl;
system("pause");
return 0;
}
Remove()_if函数:
remove_if(beg, end, op) //移除区间[beg,end)中每一个“令判断式:op(elem)获得true”的元素;op不能为一个字符
remove_if(remove和unique也是相同情况)的参数是迭代器,通过迭代器无法得到容器本身,而要删除容器内的元素只能通过容器的成员函 数来进行,因此remove系列函数无法真正删除元素,只能把要删除的元素移到容器末尾并返回要被删除元素的迭代器,然后通过erase成员函数来真正删除。
例如:
#include <iostream>
#include <algorithm> //std::remove
#include<string>
using namespace std;
bool IsSpace(char x){ return x == '5'; }
int main()
{
string s = "1, 9, 5, 4, 2, 6, 5, 7";
s.erase(remove_if(s.begin(), s.end(), IsSpace), s.end());//1,9,,4,2,6,,7
cout << s << endl;
system("pause");
return 0;
}
转载原博客:https://www.cnblogs.com/jeakeven/p/5013691.html