结构体作为STL map的key时需要注意什么? (某公司招聘面试试题)

143 篇文章 63 订阅
73 篇文章 32 订阅

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

 

 

 

 

      

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值