结构体用于STL容器
2015-08-10 14:58
330 查看
结构体用于泛型编程时,要重载小于运算符,STL里的容器都是有默认排序的,STL中的排序都是默认使用小于号来排序。因此,在对结构体排序时,我们就需要重载小于号!
主函数:
结构体作为map的key,可以将结构体转换为string,用法如下:
string strkey((const char *)&key, sizeof(key));
key是结构体,转化为变量strkey
struct Currency{ string symbol; int coins; //重载小于号 bool operator <(const Currency &A) const { int com = symbol.compare(A.symbol); if (com < 0) return true; //先比较symbol if (com == 0) return coins<A.coins?true:false; //symbol相同时,再比较coins return false; } //重载==操作符 bool operator==(const Currency &A) const { if(symbol == A.symbol && coins == A.coins) { return true; } return false; } friend ostream& operator<<(ostream &out,Currency currency);//流运算符只能定义为友元函数或普通函数,而不能定义为成员函数 }; //重载IO输出操作 ostream& operator<<(ostream &out,Currency currency) { out<<"the symbol is "<<currency.symbol<<",the coins are "<<currency.coins<<endl; return out; }
主函数:
map<Currency,string> smap; Currency value1; value1.symbol = "usa"; value1.coins = 10; smap.insert(map<Currency,string>::value_type(value1,"abc")); Currency value2; value2.symbol = "usa"; value2.coins = 10; if(value1 == value2) { cout<<"the same"<<endl; } smap.insert(map<Currency,string>::value_type(value2,"123")); for(map<Currency,string>::iterator iter = smap.begin();iter != smap.end(); ++iter) { cout<<iter->first<<"\t"<<iter->second<<endl; }
结构体作为map的key,可以将结构体转换为string,用法如下:
string strkey((const char *)&key, sizeof(key));
key是结构体,转化为变量strkey
相关文章推荐
- 【转】深入理解 Session 与 Cookie
- iOS代码实现 excel文件导出
- Android项目中如何用好构建神器Gradle?
- 九度OJ 题目1446:Head of a Gang
- hdu 1010 Tempter of the Bone
- 数据结构学习笔记3-字符串转换成整数
- c++域操作符
- Oracle + PHP 指南
- Sliding Window Maximum
- 线段树之 HDU4578Transformation
- Android onTouch事件与手势操作
- hdu 1558
- jQuery 判断所有图片加载完成
- Codevs2370 小机房的树
- UIPasteboard Example – Read, Write and Share data between apps
- JS中Cookie详解及示例展示
- 内存分配方式
- 一个服务接口的多个实现的选择
- LCS 最大子段和,最大子段和在原数组的首末地址
- 【ecos】service