模板类list中merge、remove中_Pred参数说明

本文详细介绍了C++中列表类的remove_if函数和sort函数的使用方法,包括如何通过自定义谓词来筛选元素及对列表进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <list>
using namespace std;

// a predicate implemented as a function:
bool single_digit (const int& value) { return (value<10); }

// a predicate implemented as a class:
class is_odd
{
public:
	bool operator() (const int& value) {return (value%2)==1; }
};

int main ()
{
	int myints[]= {15,36,7,17,20,39,4,1};
	list<int> mylist (myints,myints+8);   // 15 36 7 17 20 39 4 1
	mylist.remove_if (single_digit);          // 15 36 17 20 39
	mylist.remove_if (is_odd());               // 36 20	
	cout << "mylist contains:";
	for (list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
		cout << " " << *it;
	cout << endl;
	system("pause");
	return 0;
}
remove函数中指定要移除哪些值的判定函数,该函数返回值为bool类型,用于指定哪个值是要删除的。

二、list类sort函数的使用

#include <iostream>
#include <list>
using namespace std;

bool LargeToSmall(const int &left,const int &right)
{
	return (right < left);
} 

int main ()
{
	int a[5]={3,1,9,2,6};
	list<int> lista(a,a+5);
	//注意是LargeToSmall,而不是LargeToSmall( )
	lista.sort(LargeToSmall);
	for (auto i:lista)
	{
		cout<<i<<"  ";
	}
	cout<<endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值