结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(_)~~~~
生活随笔
收集整理的這篇文章主要介紹了
结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(_)~~~~
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
某公司招聘的面試環(huán)節(jié), 有這樣一個(gè)題目:結(jié)構(gòu)體作為STL map的key時(shí)需要注意什么? 對(duì)于懂STL map的同學(xué)來說, 這個(gè)題目還是比較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;
}
運(yùn)行一下, 發(fā)現(xiàn)程序是有錯(cuò)誤的。 為什么呢? 原來, 對(duì)于map來說, key必須是有序的, 也就是說, key與key之間必須能比較, 所以需要重載<號(hào), 因此, 上述程序錯(cuò)誤, 應(yīng)該改為: #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; }
運(yùn)行正確, 結(jié)果為:
cat
eric
OK, 本文先討論到這里, 關(guān)鍵是要對(duì)map的“關(guān)鍵字有序”有足夠的認(rèn)識(shí)。
運(yùn)行一下, 發(fā)現(xiàn)程序是有錯(cuò)誤的。 為什么呢? 原來, 對(duì)于map來說, key必須是有序的, 也就是說, key與key之間必須能比較, 所以需要重載<號(hào), 因此, 上述程序錯(cuò)誤, 應(yīng)該改為: #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; }
運(yùn)行正確, 結(jié)果為:
cat
eric
OK, 本文先討論到這里, 關(guān)鍵是要對(duì)map的“關(guān)鍵字有序”有足夠的認(rèn)識(shí)。
總結(jié)
以上是生活随笔為你收集整理的结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(_)~~~~的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL MAP(key,value)
- 下一篇: map和vector的迭代器失效问题(某