学习笔记:C++关于map中key与value皆为结构体时的用法demo

最近在学习C++有一个需求:我希望构建一个map,其中key为一个结构体,这个结构体中包括他的名字和年龄;map的value为数组,为了方便处理,我将其处理为了另一个结构体,结构体中包括了一个三门成绩的整型数组。

 

代码如下:

#include <iostream>
#include <map>
struct Man{
	std::string name;
	int age;
	bool operator<(const Man& g)const { 
		if (age < g.age) { 
			return true; 
		} 
		return false; 
	} 

};

struct Tripple 
{ 
    int score [ 3 ]; 
}; 




int main() {
	std::map<Man, Tripple > Infos ; 
	
	Tripple  triple_score1 = {70,80,90}; 

	Man man1,man2,man3;
	man1.name = "Lucy";
	man1.age = 20;
	man2.name = "July";
	man2.age = 21;
	man3.name = "James";
	man3.age = 22;
        Infos[man1]=triple_score1;

 
	for(std::map<Man, Tripple>::iterator iter = Infos.begin(); iter != Infos.end(); ++iter) {
		std::cout << iter->second.score[0]<< std::endl;
		std::cout << iter->second.score[1]<< std::endl;
		std::cout << iter->second.score[2]<< std::endl;
	}
	return 0;
}

最开始我是想往map的value中塞一个数组,关于这种用法网上资源也不多,后来发现CSDN有人建议将数组改为结构体。当我试着这样处理后,发现能够完美解决问题。小小的记录下,一是自己做个备忘,二是希望能帮助到未来有需要的人。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值