仿函数和判断式的使用

一元判断式的使用


#include<iostream>
#include<list>
#include<algorithm>
#include"Header.h"
#include<cstdlib>
/*
一元判断式
*/
using namespace std;


bool IsPrimary(int number)
{
number = abs(number);
if (number == 0 || number == 1)
return true;


int div;
for (div =number/2 ; number%div != 0; --div)
{
;
}


return div == 1;


}


int main(){
list<int> coll1;


for (int i = 24; i <= 30; ++i){
coll1.push_back(i);
}
Print_Elements(coll1, "init:   ");
list<int>::iterator pos;
pos = find_if(coll1.begin(), coll1.end(), IsPrimary);
if (pos != coll1.end())
{
cout << *pos << "is first prime number found" << endl;
}
else{
cout << "no primary number found" << endl;
}


getchar();
getchar();


}


二元判断式的 使用


#include<iostream>
#include<string>
#include<deque>
#include<algorithm>
using namespace std;
/*
二元判断式
*/


class Person{
public:
string firstname()const;
string secondname()const;


};


bool personSort(const Person& p1, const Person& p2){
return p1.firstname() < p2.firstname() ||
(!(p2.firstname() < p1.firstname()) &&
p1.secondname() < p2.secondname());
}




int main()
{
deque<Person> coll1;


sort(coll1.begin(), coll1.end(), personSort);


}


仿函数的使用:
/*
仿函数是指行为像个函数,比如你定义了一个对象,你可以把它当做函数来使用
函数行为是指:
function(arg1,arg2);
*/


#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class PrintInt{
public:
void operator()(int elem)const{
cout << elem << " ";
}




};


int main()
{
vector<int> coll1;
for (int i = 1; i <= 9; ++i){
coll1.push_back(i);
}


// copy(coll1.begin(), coll1.end(), PrintInt());
for_each(coll1.begin(), coll1.end(), PrintInt());
cout << endl;


getchar();
getchar();
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值