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;
}

运行结果:



代码示例:

#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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`std::ptr_fun`是C++标准库中的一个函数模板,位于头文件`<functional>`中。它可以将普通函数指针或函数对象转换为函数适配器,以便在算法中使用。 `std::ptr_fun`的定义如下: ```cpp template <typename Arg, typename Result> std::pointer_to_unary_function<Arg, Result> ptr_fun(Result (*f)(Arg)); ``` 参数`f`是一个普通函数指针,它指向一个接受类型为`Arg`的参数并返回类型为`Result`的函数。 `std::ptr_fun`函数模板返回一个`std::pointer_to_unary_function`类型的函数适配器对象,该对象可以将其参数应用于传入的函数指针。 以下是一个简单的示例,展示了如何使用`std::ptr_fun`将普通函数指针转换为函数适配器,并在算法中使用它: ```cpp #include <iostream> #include <algorithm> #include <vector> #include <functional> // 普通函数 bool isEven(int num) { return num % 2 == 0; } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 将普通函数指针转换为函数适配器 std::function<bool(int)> isEvenAdapter = std::ptr_fun<int, bool>(isEven); // 使用函数适配器进行判断 auto it = std::find_if(numbers.begin(), numbers.end(), isEvenAdapter); if (it != numbers.end()) { std::cout << "找到了第一个偶数:" << *it << std::endl; } else { std::cout << "未找到偶数" << std::endl; } return 0; } ``` 输出结果: ``` 找到了第一个偶数:2 ``` 在上面的示例中,我们定义了一个名为`isEven`的普通函数,用于判断一个整数是否为偶数。然后,我们使用`std::ptr_fun`将普通函数指针`isEven`转换为函数适配器`isEvenAdapter`。最后,我们使用函数适配器`isEvenAdapter`在容器`numbers`中查找第一个满足条件的元素。最终找到了第一个偶数2并输出。 需要注意的是,C++11之后,可以直接使用lambda表达式或者函数对象代替`std::ptr_fun`来实现相同的功能,更加简洁方便。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值