某公司招聘的面试环节, 有这样一个题目:结构体作为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的“关键字有序”有足够的认识。

 

 

 

 

      

 


本文转载:CSDN博客