最近在学习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有人建议将数组改为结构体。当我试着这样处理后,发现能够完美解决问题。小小的记录下,一是自己做个备忘,二是希望能帮助到未来有需要的人。