C++ map以自定义数据类型做键值

来源:互联网 发布:网络海报设计 编辑:程序博客网 时间:2024/06/08 19:44

前言

作者最近在项目开发中遇到一个问题,想采用自定义的结构体作为键值,但是无论怎样,就连编译都不能通过,针对这个问题,作者就开始寻求解决的办法.。终于这个问题得以解决,高兴之余,决定写个例子,供大家参考

1.map在STL中的定义

template<class Key, class T, class Pred = less<Key>, class A = allocator<T> >
第一个参数 Key: map的关键字类型
第二个参数T:      map的值类型
第三个参数:        比较函数Compare(仿函数)
第四个参数:         内存配置对象      
map内部存储机制实际是以红黑树为基础,红黑树在插入节点时,必须按照大小比较之后在一个合适的为止进行插入动作,map默认的比较函数Compare为less,所以作为键值插入,则必须有小于号“<”这个比较操作附,众所周知,int,double,string等作为键值时,都有内置比较函数,与map搭配无论是插入还是查找,都没有什么问题,但作为复杂的数据类型(结构体,类),一般我们定义这些类型都不会有意识的重载operator<;因此,自定义数据类型,就不能直接作为map的键值,那么,如何使自定义的数据类型作为map的键值呢?

2.自定义数据类型做map键值

要使结构体、类能够作为map的键值,那么首先必须使这些数据类型支持operator<操作.

引用到的头文件

#include <intsafe.h>#include <string>#include <map>using namespace std;

Time结构体定义

struct Time{UINT16 nYear;UINT8 nMonth;UINT8 nDay;UINT8 nHour;UINT8 nMinute;UINT8 nSecond;UINT16 nTick;Time(){}Time(UINT16 nYear,UINT8 nMonth,UINT8 nDay,UINT8 nHour,UINT8 nMinute,UINT8 nSecond,UINT16 nTick){this->nYear = nYear;this->nMonth = nMonth;this->nDay = nDay;this->nHour = nHour;this->nMinute = nMinute;this->nSecond = nSecond;this->nTick = nTick;}Time(const Time &stTime){*this = stTime;}bool operator<(const Time& stTime) const{//比较年if (this->nYear < stTime.nYear){return true;}else if (this->nYear == stTime.nYear){//比较月份if (this->nMonth < stTime.nMonth){return true;}else if (this->nMonth == stTime.nMonth){//比较dayif (this->nDay < stTime.nDay){return true;} else if (this->nDay == stTime.nDay){//比较nHourif (this->nHour < stTime.nHour){return true;}else if(this->nHour == stTime.nHour){//比较分钟if (this->nMinute < stTime.nMinute){return true;}else if (this->nMinute == stTime.nMinute){if (this->nSecond < stTime.nSecond){return true;}else if (this->nSecond == stTime.nSecond){if (this->nTick < stTime.nTick){return true;}else{return false;}}else{return false;}}else{return false;}}else{return false;}}else{return false;}}else{return false;}}else{return false;}}};typedef map<Time,string> TMap;

测试代码:

int main(void){Time stKeyF(2015,02,14,18,22,55,100);Time stKeyS(2015,02,14,18,22,55,101);Time stKeyT(2014,02,14,18,22,55,101);TMap timeMap;timeMap.insert(make_pair(stKeyF,"C# Language"));timeMap.insert(make_pair(stKeyS,"C++ Language"));timeMap.insert(make_pair(stKeyT,"C Language"));return EXIT_SUCCESS;}

测试调试结果:






0 0
原创粉丝点击