结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(_)~~~~
生活随笔
收集整理的這篇文章主要介紹了
结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)已跪~~~~(_)~~~~
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
某公司招聘的面試環節, 有這樣一個題目:結構體作為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的“關鍵字有序”有足夠的認識。
運行一下, 發現程序是有錯誤的。 為什么呢? 原來, 對于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,value)
- 下一篇: map和vector的迭代器失效问题(某