C++标准库---ptr_fun()

ptr_fun是将一个普通的函数适配成一个仿函数(functor), 添加上argument_type和result type等类型.


例如:

#include <algorithm>  
#include <functional>  
#include <iostream>  

using namespace std;  

int sum(int arg1, int arg2)  
{  
	std::cout<< "arg1 = " << arg1 << std::endl;  
	std::cout<< "arg2 = " << arg2 << std::endl;  

	int sum = arg1 + arg2;  
	std::cout << "sum = " << sum << std::endl;  

	return sum;  
}

int main(int argc, char *argv[], char *env[])
{  
	bind1st(ptr_fun(sum), 1)(2);		// the same as sum(1,2)  
	bind2nd(ptr_fun(sum), 1)(2);		// the same as sum(2,1)  

	system("pause");
	return 0;
}

运行结果:

C++标准库---ptr_fun()_第1张图片


代码示例:

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<string>

using namespace std;

int main()
{
	vector<char*> coll;
	vector<char*>::iterator iter1,iter2;

	coll.push_back("lan");
	coll.push_back("zhi");
	coll.push_back("hui");
	coll.push_back("is");
	coll.push_back("a");
	coll.push_back("good");
	coll.push_back("boy!");

	for(iter1=coll.begin();iter1!=coll.end();++iter1)
	{
		cout<<*iter1<<" ";
	}
	cout<<endl;

	iter2=find_if(coll.begin(),coll.end(),not1(bind2nd(ptr_fun(strcmp),"hui")));//hui与coll中所有字符串比较,如果相同,则反相后输出

	if(iter2!=coll.end())
	{
		cout<<"Found: "<<*iter2<<endl;
	}
	else
	{
		cout<<"Not Found"<<endl;
	}

	system("pause");
	return 0;
}
运行结果:

lanzhihui is a good boy

Found: hui

你可能感兴趣的:(C++,库,仿函数,ptr_fun)