#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的“關鍵字有序”有足夠的認識。