结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
来源:互联网 发布:linux怎么退出man 编辑:程序博客网 时间:2024/04/30 18:07
转载自:http://blog.csdn.net/stpeace/article/details/46553525
某公司招聘的面试环节, 有这样一个题目:结构体作为STL map的key时需要注意什么? 对于懂STL map的同学来说, 这个题目还是比较easy的, 先看程序:
#include <iostream>#include <string>#include <map>using namespace std;struct Info{ string name; int score;};int main(){ Info a, b; a.name = "eric"; a.score = 90; b.name = "cat"; b.score = 85; map<Info, int> m; m[a] = 1; m[b] = 2; return 0;}
运行一下, 发现程序是有错误的。 为什么呢? 原来, 对于map来说, key必须是有序的, 也就是说, key与key之间必须能比较, 所以需要重载<号, 因此, 上述程序错误, 应该改为:
#include <iostream>#include <string>#include <map>using namespace std;struct Info{ string name; int score; bool operator< (const Info &x) const { return score < x.score; }};int main(){ Info a, b; a.name = "eric"; a.score = 90; b.name = "cat"; b.score = 85; map<Info, int> m; m[a] = 1; m[b] = 2; map<Info, int>::iterator it; for(it = m.begin(); it != m.end(); it++) { cout << it->first.name << endl; } return 0;}
运行正确, 结果为:
cat
eric
OK, 本文先讨论到这里, 关键是要对map的“关键字有序”有足够的认识。
0 0
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(>_<)~~~~
- struct作为map的key时,需要重载该结构体
- 字符串的大小比较(某公司校园招聘面试试题)
- 如何判断平面上两条线段(注意是线段)是否相交?(某公司校园招聘面试试题)
- C++结构体作为map的key的时候需要重载<运算符
- 结构体作为map的key或放入set中,需要重载<运算符
- 结构体作为map的key或放入set中,需要重载<运算符
- 聊聊map和vector的迭代器失效问题(某公司招聘笔试试题)
- 聊聊map和vector的迭代器失效问题(某公司招聘笔试试题)
- map和vector的迭代器失效问题(某公司招聘笔试试题)
- groovy 使用变量值作为 map 的key--需要注意的
- 【C++】自定义结构体作为map的key
- map结构体作为key值的使用
- AVL树(考研的同学需要注意其定义)的判定(某公司2012年校园招聘笔试题目)
- AVL树(考研的同学需要注意其定义)的判定(某公司2012年校园招聘笔试题目)
- STL map中key为结构体的用法
- 蓝牙虐我
- (转载)git 创建远程仓库详解
- LeetCode-111. Minimum Depth of Binary Tree
- tomcat配置
- ACLlib 里的定时器
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
- TortoiseSvn和Subclipse对应关系
- react-native环境搭建问题
- python抽取指定url页面的title
- Spark笔记
- 做项目总结1
- 链表的逆序打印
- PHP中使用CURL模拟登录并获取数据实例
- MySQL查询缓存设置 提高MySQL查询性能