关于 STL 的 remove_if

本文详细解析了STL中的remove_if函数,阐述其工作原理、使用方法及与erase-remove idiom的关系,通过示例展示了如何从容器中移除符合条件的元素。

关于 STL 的 remove_if


转自:https://blog.youkuaiyun.com/u010982765/article/details/77619285

函数原型:

#include <algorithm>
forward_iterator remove_if( forward_iterator start, forward_iterator end, Predicate p );

函数remove_if()移除序列[start, end)中所有应用于谓词p返回true的元素.
此函数返回一个指向被修剪的序列的最后一个元素迭代器.

记住, remove_if()并不会实际移除序列[start, end)中的元素;
如果在一个容器上应用remove_if(), 容器的长度并不会改变(remove_if()不可能仅通过迭代器改变容器的属性), 所有的元素都还在容器里面.

实际做法是, remove_if()将所有应该移除的元素都移动到了容器尾部并返回一个分界的迭代器. 移除的所有元素仍然可以通过返回的迭代器访问到. 为了实际移除元素, 你必须对容器自行调用erase()以擦除需要移除的元素. 这也是erase-remove idiom名称的由来:

container.erase(remove_if(container.begin(), container.end(), pred), container.end());

remove_if()类似于partition(), 但有两点不同: 1) 它们使用的谓词条件刚好相反. 2) remove_if只强调前面部分(第二部分不再需要了)
remove_if()以线性时间(linear time)运行.
remove_if()不能用于关联容器如set<>或map<>.

测试代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include "print.h"   // 打印元素
using namespace std;
 
int main()
{
	vector<int> coll;
	for (int i = 1; i <= 9; ++i)
		coll.push_back(i);
	PRINT_ELEMENTS(coll);    // 打印元素
	vector<int>::iterator pos;
	pos = remove_if(coll.begin(),coll.end(),
			bind2nd(less<int>(),7));    
 
	coll.erase(pos,coll.end());
	PRINT_ELEMENTS(coll);
	cout << endl;
	return 0;
}

运行结果:

1 2 3 4 5 6 7 8 9
7 8 9

在这里插入图片描述
print.h如下:

#include <iostream>
 
template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const char* opt = "")
{
	typename T::const_iterator pos;
	std::cout << opt;
	for (pos = coll.begin(); pos != coll.end(); ++pos)
	{
		std::cout << *pos << " ";
	}
	std:cout << std::endl;
}

————————————————
版权声明:本文为优快云博主「initMyHeart」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/u010982765/article/details/77619285

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值