判断式是一个返回boolean值的韩叔叔,通常被用来指定排序准则和搜索准则。
一 Unary Predicates(一元判断式)
检查唯一参数的某项特性:
如:搜索第一个质数:
#include<iostream>
#include<list>
#include<algorithm>
#include<cstdlib>
using namespace std;
bool isPrime(int number)
{
//ignore negative sign
number = abs(number);
//0 and 1 are prime numbers
if (number==0 || number==1)
{
return true;
}
int divisor;
for(divisor=number/2;number%divisor !=0;--divisor);
return divisor == 1;
}
int main()
{
list<int>coll;
//insert element from 24 to 50
for(int i=24;i<50;++i)
{
coll.push_back(i);
}
//search for prime number
list<int>::iterator pos;
pos=find_if(coll.begin(),coll.end(),//range
isPrime);//predicate
if(pos !=coll.end())
cout<<*pos<<" is first prime number found"<<endl;
else
{
cout<<"no prime number found"<<endl;
}
return 0;
}
输出:
Binary Predicates
比较两个参数的特定属性
#include<iostream>
#include<list>
#include<algorithm>
#include<cstdlib>
#include<deque>
using namespace std;
class Person
{
public:
Person();
~Person();
public:
string firstname()const;
string lastname()const;
};
bool PersonSortCriterion(const Person&p1,const Person&p2)
{
return p1.firstname<p2.firstname ||
(!(p2.lastname<p1.lastname) &&
p1.firstname<p2.firstname);
}
int main()
{
deque<Person>coll;
sort(coll.begin(),coll.end(),
PersonSortCriterion);
}