remove和remove_if区别

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

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值