结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
2017-03-01 15:29
495 查看
转载自:http://blog.csdn.net/stpeace/article/details/46553525
某公司招聘的面试环节, 有这样一个题目:结构体作为STL map的key时需要注意什么? 对于懂STL map的同学来说, 这个题目还是比较easy的, 先看程序:
运行一下, 发现程序是有错误的。 为什么呢? 原来, 对于map来说, key必须是有序的, 也就是说, key与key之间必须能比较, 所以需要重载<号, 因此, 上述程序错误, 应该改为:
运行正确, 结果为:
cat
eric
OK, 本文先讨论到这里, 关键是要对map的“关键字有序”有足够的认识。
某公司招聘的面试环节, 有这样一个题目:结构体作为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的“关键字有序”有足够的认识。
相关文章推荐
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(>_<)~~~~
- 结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)
- 以自定义对象作为hashmap的key需要注意什么
- 如何判断平面上两条线段(注意是线段)是否相交?(某公司校园招聘面试试题)
- 2007年初某IT公司招聘网络管理员面试考试试题(答案)
- 如何你是公司的HR,去招聘asp.net程序员,你会对前来面试的人问什么问题。
- 如何在VC++6.0中设置条件断点?--- 某公司实习生招聘面试试题
- 单链表的就地逆置 (单链表带头结点)(某公司校园招聘面试试题)
- IT软件外包行业深入分析:现状、前途、趋势、待遇 什么是软件外包 外包公司是怎么工作的 软件外包公司的面试 软件外包公司需要什么样的人
- 简单详解:x^6+4x^4+2x^3+x+1 至少要需要多少次乘法? (某公司实习生招聘笔试试题)
- 构造函数可以是虚函数吗? 为什么?(某公司实习生招聘面试试题)
- struct作为map的key时,需要重载该结构体
- 面试产品经理需要注意什么
- 中国公司进行海外招聘应该注意什么?
- 中国公司进行海外招聘应该注意什么?
- 面试 需要注意三种公司
- 字符串的大小比较(某公司校园招聘面试试题)
- IT公司面试时需要注意的几个题目(最近面试几个IT公司的感受)
- AVL树(考研的同学需要注意其定义)的判定(某公司2012年校园招聘笔试题目)
- 结构体作为map的key或放入set中,需要重载<运算符