以下模板可以用来生成函数对象:
- 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;
}
结果如下: