STL之函数对象

在STL当中如果元素,或者说key的类型不是默认数据类型的话,我们需要自己定义比较函数对象,查找函数对象,以及哈希函数对象,我呢,自己写了这个例子,只是语法上合乎

规范,让自己记住下,恩

// 函数对象.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<hash_map>
#include<algorithm>
using namespace std;
struct stuInfo
{
	int num;//学号
	char name[20];//姓名
};
struct infoEqual
{
	static const int bucket_size=95;
	//比较函数对象,确定是否能插入
	bool operator()(const stuInfo a,const stuInfo b)const
	{
		return (a.num==b.num)&&(strcmp(a.name,b.name)==0);
	}
	//哈希函数对象,用于确定放在哪个bucket当中
	size_t operator()(const stuInfo a)const
	{
		return a.num;
	}
};
//查找函数对象
class cus_find
{
public :
	char name[30];
	int num;
	cus_find(char*s,int a)
	{
		strcpy(name,s);
		num=a;
	}
	bool operator()(pair<stuInfo,char*> a)
	{
		return (strcmp(a.first.name,name)==0)&&(a.first.num==num);		
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	hash_map<stuInfo,char*,infoEqual>hh;
	stuInfo h={12,"苏轼"};
	char *hn="苏轼";
	hh[h]=hn;

	hash_map<stuInfo,char*,infoEqual>::iterator itr=find_if(hh.begin(),hh.end(),cus_find("苏轼",12));
	if(itr!=hh.end())
	{
		cout<<"找到了该生信息"<<endl;
		cout<<"\t"<<(*itr).first.name<<endl;
	}
	return 0;
}
这个过程不是很舒服,不过好在已经弄出来了,哈哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值