码迷,mamicode.com
首页 > 其他好文 > 详细

Vector的仿函数用法

时间:2017-07-22 22:40:53      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:16px   val   return   opera   log   变量   type   成员   div   

一,概述        

仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。   有些功能的的代码,会在不同的成员函数中用到,想复用这些代码。

                            1)公共的函数,可以,这是一个解决方法,不过函数用到的一些变量,就可能成为公共的全局变量,再说为了复用这么一片代码,就要单立出一个函数,也不是很好维护。

                            2)仿函数,写一个简单类,除了那些维护一个类的成员函数外,就只是实现一个operator(),在类实例化时,就将要用的,非参数的元素传入类中

 

http://blog.csdn.net/tianshuai1111/article/details/7687983

仿函数find_if的用法:

http://www.cnblogs.com/motadou/archive/2009/02/01/1561549.html

http://blog.csdn.net/hj490134273/article/details/6051080

http://www.cnblogs.com/motadou/archive/2009/02/01/1561549.html

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct 
{
	int age;
	int studentid;
}student;
/**************vector仿函数*******************/
class vector_finder
{
public:
	vector_finder(const int &a,const int &b):m_v_a(a),m_v_b(b){}
	bool operator()(vector<student>::value_type & value)
	{
		return ((value.age ==m_v_a)&&(value.studentid==m_v_b));
	}
private:
	int m_v_a;
	int m_v_b;
};
int main()
{
	vector<student> vec;
	student stu;
	stu.age=10;
	stu.studentid=0;
	vec.push_back(stu);
	stu.age=11;
	stu.studentid=1;
	vec.push_back(stu);
	stu.age=12;
	stu.studentid=2;
	vec.push_back(stu);
	
	vector<student>::iterator it=find_if(vec.begin(),vec.end(),vector_finder(12,2));
	if(vec.end()==it)
	{
		printf("mu you zhaodao \r\n");
	}
	else
	{
		printf("位置 age[%d]stuid[%d]\r\n",it->age,it->studentid);
	}
	

	return 0;
}

 

Vector的仿函数用法

标签:16px   val   return   opera   log   变量   type   成员   div   

原文地址:http://www.cnblogs.com/cheshl/p/7222761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!