remove_if

 
// remove_if.cpp -- 2011-10-03-16.00
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

using std ::vector ;
using std ::equal_to ;

template<class T>
class Print
{
public:
	void operator () (const T & t) const
	{
		std ::cout << t << " " ;
	}
} ;

int _tmain(int argc, _TCHAR* argv[])
{
	int arr1[] = {1, 3, 6, 1, 0, 9, 0, 7, 0, 5, 0} ;
	vector<int> vec1(arr1, arr1 + sizeof arr1 / sizeof (int)) ;

	//	remove_if (beg, end, val, unaryPred) ;
	//	操作前:[beg,end)指示输入迭代器.val是要删除的元素.unaryPred是一元函数对象.
	//	操作后:删除输入序列中使unaryPred返回true的元素.被删除的元素使用后续元素依次进行填充.
	//	返回值:返回指向未删除的最后一个元素的下一个位置的迭代器.
	//	备注:		算法运行结束后原始输入序列的大小并未改变.
	//					后续元素空出的位置使用原序列中的相应位置的元素进行填充,无论其中的元素
	//					是否要求被删除.
	vector<int> ::iterator iter = remove_if(vec1.begin(), vec1.end(), bind2nd(equal_to<int> (), 0)) ;
	if (iter != vec1.end())
		std ::cout << *iter << std ::endl ;
	for_each(vec1.begin(), vec1.end(), Print<int> ()) ;

	std ::cin.get() ;

	return 0 ;
}
这三个函数是 STL 算法中用于删除元素的函数。它们的作用分别是: - `remove_if`:删除满足指定条件的元素,返回指向新的逻辑结尾的迭代器。 - `remove_copy`:将满足指定条件的元素拷贝到另一个容器中,返回指向新的逻辑结尾的迭代器。 - `remove_copy_if`:将不满足指定条件的元素拷贝到另一个容器中,返回指向新的逻辑结尾的迭代器。 下面是它们的用法和示例: ```cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { // remove_if vector<int> v1{1, 2, 3, 4, 5}; auto it1 = remove_if(v1.begin(), v1.end(), [](int x) { return x % 2 == 0; }); v1.erase(it1, v1.end()); for (int x : v1) { cout << x << " "; // 输出 1 3 5 } cout << endl; // remove_copy vector<int> v2{1, 2, 3, 4, 5}; vector<int> v3; remove_copy(v2.begin(), v2.end(), back_inserter(v3), [](int x) { return x % 2 == 0; }); for (int x : v3) { cout << x << " "; // 输出 1 3 5 } cout << endl; // remove_copy_if vector<int> v4{1, 2, 3, 4, 5}; vector<int> v5; remove_copy_if(v4.begin(), v4.end(), back_inserter(v5), [](int x) { return x % 2 == 0; }); for (int x : v5) { cout << x << " "; // 输出 1 3 5 } cout << endl; return 0; } ``` 注意,这三个函数并不真正删除容器中的元素,而是返回指向新的逻辑结尾的迭代器。如果要真正删除元素,需要结合容器的 `erase` 函数使用。此外,`remove_copy` 和 `remove_copy_if` 会将满足条件的元素拷贝到另一个容器中,因此要注意目标容器的类型和大小。在示例中,使用了 `back_inserter` 函数将元素插入 `vector` 的尾部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值