STL中的函数对象类模板

以下模板可以用来生成函数对象:

  • equal_to
  • greater
  • less
    头文件 functional
    greater 的应用
    list有两个sort成员函数
  • void sort()
    将list中的元素按照 "<"规定的方法升序排列,
  • template
    void sort( Compare op);
    将list中的元素按照op规定的比较方法升序排列。即要比较x和y的大小时,看op( x , y )的返回值,为true认为x小于y。
    代码:
	#include <list>
	#include <iostream>
	using namespace std;
	class MyLess
	{
		public:
			bool operator()( const int &c1 , const int &c2 )
			{
	 			return ( c1 % 10 ) < ( c2 % 10 ) ;
			}
	};
	template < class T >
	void print( T first , T last )
	{
		for( ; first != last ; first++ )
		{
		   cout << *first << " , ";
		}
	}
	int main()
	{
		const int SIZE = 5 ;
		int a[SIZE] = { 5 , 21 , 14 , 2 , 3 };
		list<int> list1( a , a + SIZE );
		list1.sort( MyLess() );
		print( list1.begin() , list1.end() );
		cout << endl;
		list1.sort( greater<int>() );// greater<int>() 是个对象
		print( list1.begin() , list1.end() );
		cout << endl;
		return 0 ;
	}

在这里插入图片描述
在这里插入图片描述
写出MyMax函数函数模板

	#include <iostream>
	#include <iterator>
    using namespace std;
    class Myless
    {
		bool operator()( int a1 , int a2 )
		{
			if( ( a1 % 10 ) < ( a2 % 10 ) )
			{
				return true;
			} 
			else
			{
				return false;
			}
		}
	};
	bool MyCompare( int a1 , int a2 )
	{
		if( ( a1 % 10 ) < ( a2 % 10 ) )
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// MyMax函数模板
	T MyMax( T first , T last , Pred myless )
	{
		T tempMax = first ;
		for( ; first != last ; first++ )
		{
			if( myless( *tempMax , *first ) )
			{
				tempMax = first;
			}
		}
		return tempMax;
	}
	int main()
	{
		int a[] = { 35 , 7 , 13 , 19 , 2 };
		cout << *MyMax( a , a + 5 , MyLess ) << endl;
		cout << *MyMax( a , a + 5 , MyCompare ) << endl;
		return 0;
	}

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百万攻城狮

你的鼓励是我最大的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值