結構體作爲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的“關鍵字有序”有足夠的認識。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章