c++ map key为结构体
来源:互联网 发布:只有我知2在线看 编辑:程序博客网 时间:2024/05/18 02:36
项目中需要将结构体作为hash的key,一开始用hash_map,但是结构体中多值比较一直失败,所以尝试了map。
hash_map 查找速度会比map快,而且查找速度基本和数据量大小无关,属于常数级别;而map的查找速度是log(n)级别。hash还有hash函数的耗时。当有100w条记录的时候,map也只需要20次的比较,200w也只需要21次的比较!所以并不一定常数就比log(n) 小。
hash_map对空间的要求要比map高很多,所以是以空间换时间的方法,而且,hash_map如果hash函数和hash因子选择不好的话,也许不会达到你要的效果,
#include <string>#include <cstring>#include <iostream>#include <map>using namespace std;typedef struct ip_tuple{ int src_port; int dst_port; char* src_ip; bool operator <(const ip_tuple& other) const { if (src_port < other.src_port) //src_port按升序排序 { return true; } else if (src_port == other.src_port) //src_port相同,按dst_port升序排序 { if(dst_port < other.dst_port) { return true; } else if(dst_port == other.dst_port)//dst_port,src_port相同,比较src_ip { if(strcmp(src_ip,other.src_ip)!=0) { return true; } } } return false; }} IPTUPLE;int main(){ map<IPTUPLE, int>m_roadMap; for(int i=1; i<6; i++) { IPTUPLE it; it.src_port = i; it.dst_port = i*10; if(i==1) it.src_ip="aaa"; if(i==2) it.src_ip="bbb"; if(i==3) it.src_ip="ccc"; if(i==4) it.src_ip="ddd"; if(i==5) it.src_ip="bbb"; m_roadMap.insert(make_pair(it, i*200)); }//========== IPTUPLE ite; ite.src_port = 2; ite.dst_port = 20; ite.src_ip="bbb"; map<IPTUPLE, int>::iterator itor; itor = m_roadMap.find(ite); if (itor != m_roadMap.end()) { cout<<itor->second; }}
0 0
- c++ map key为结构体
- Map的key为自定义结构体
- STL map中key为结构体的用法
- STL map中key为结构体的用法
- STL map中key为结构体的用法
- STL map中key为结构体的用法
- c++ map中key为类对象或结构体
- STL map中key为结构体的用法
- map中key为结构体的用法
- STL map中key为结构体的用法
- STL map中key为结构体的用法
- STL map中key为结构体的用法
- key为自定义结构的map
- map key值为结构的写法
- 【C++】自定义结构体作为map的key
- map的key元素为结构体时该结构体需重截操作符<
- C++ map以结构体为key的编译错误和解决方法
- C++map key不存在
- Android屏幕适配解析
- 子代理扩搌
- 飞机大战之二:主角飞机登场
- 平凡人 我喜欢
- C# 构造函数说明
- c++ map key为结构体
- MyEclipse中web项目改名后部署路径不变的解决方法
- 浏览器窗口加载和大小改变事件
- extern和const的用法
- cin对象支持的3种模式的单字符输入
- android 相对布局
- Tomcat:Caused by: java.lang.OutOfMemoryError: PermGen space
- 致理想
- 追踪uboot下tftp命令的代码执行过程-Nagul