map 自定义类型作为键值
来源:互联网 发布:手机网络捕鱼修改器 编辑:程序博客网 时间:2024/06/12 01:06
作为一个计算机专业的学生,一直没有深入的学习过map真是罪过罪过!
今天终于对map的insert机制做了一点研究,弄明白了如何用自定义类型作为键值了。
网上大多数的言论都是必须重载“<"操作符,但其实不止要重载"<"操作符,还需重载"=="操作符才能更好的完成工作。对于一个自定义类型, 重载”<“操作符一定要合适,即对于自定义类型A的两个对象a,b,如果a < b == false, 则b < a 必须==true,否则会出现invalid operator<这个错误。不得不佩服STL的编写者,太牛叉了!
废话不多说,上代码最好。
#ifndef GGI_H#define GGI_Hclass GGI{public:int a; int b;GGI();GGI(int a, int b);friend bool operator==(const GGI& the, const GGI& other);friend bool operator<(const GGI& the, const GGI& other);};#endif
#include "GGI.h"GGI::GGI(){this->a = 0;this->b = 0;}GGI::GGI(int a, int b){this->a = a;this->b = b;}bool operator<(const GGI& the, const GGI& other){return (the.a < other.a && the.b < other.b) || (the.a < other.a && the.b > other.b) ||(the.a < other.a && the.b == other.b) ||(the.a == other.a && the.b < other.b);}bool operator==(const GGI& the, const GGI& other){return (the.a == other.a && the.b == other.b);}
#include "GGI.h"#include <iostream>#include <map>#include <fstream>#include <cassert>#include <string>#include <sstream>using namespace std;int main(){map<GGI, float> mg;pair<map<GGI, float>::iterator, bool> mapInsertPair;ifstream fin("human.txt");assert(fin);while(!fin.eof()){string line = "";getline(fin, line);istringstream iss(line);int a, b;float c;iss >> a >> b >> c;GGI* g = (a < b ? new GGI(a,b) : new GGI(b,a));mapInsertPair = mg.insert(pair<GGI, float>(*g, c));if(!mapInsertPair.second){if(c > mapInsertPair.first->second)mapInsertPair.first->second = c;}}for(map<GGI, float>::iterator mi = mg.begin(); mi != mg.end(); ++mi){cout << mi->first.a << '\t' << mi->first.b << '\t' << mi->second << '\n';}
fin.close();system("pause");return 0;}
上面是正确的代码。
但是有一个问题还没弄明白就是如果不重载==操作符,也是可以工作的,这其中也有可以插入成功的,也有失败的,程序内部是怎么判断是否插入成功呢? 还望各位能不吝赐教。
- map 自定义类型作为键值
- std::map 如何使用结构体作为自定义键值
- std::map 如何使用结构体作为自定义键值
- map以自定义类型当Key(键值)
- map以自定义类型当Key(键值)
- map以自定义类型当Key(键值)
- 使用用户自定义类型作为std::map的key
- 使用用户自定义类型作为std::map的…
- md5值 作为map<string,time_t>键值
- C++笔记:map键值类型,元素删除
- Map以自定义类做为键值
- Map以自定义类做为键值
- Map以自定义类做为键值
- Map以自定义类做为键值
- Map以自定义类做为键值
- JS自定义 Map 键值对对象
- Map以自定义类做为键值
- C++ map以自定义数据类型做键值
- Matlab textread函数详解
- Does the RTSP implementation (client and/or server) support 'trick mode' operations
- VPN与NET地址转换
- LUA require 搜索路径指定方法
- 位图缩放的快速方法
- map 自定义类型作为键值
- Preference 的xml使用 小结
- SQL事务的用法
- webLogic后台运行(Unix/lunix)
- 怎样去除PDF中的空白页 - GdPicture.NET使用教程
- asp.net 负载均衡下session存储的解决方法
- 关于DW建模中维度建模问题一:自己循环
- Windbg和VirtualBox通过虚拟串口调试Win 8
- 获取当前模型的文件路径