c++ - How can I make a map where the value is an array of structs in C++
问题描述
I have the following structure.
struct Tourist {
string name;
string surname;
string sex;
};
I would like to sort tourists by families.
int getMinRoomsAmount(Tourist touristsList[]) {
map<string, Tourist[]> families;
for (int i=0; i < 40; i++) {
families[touristsList[i].surname] = // to append the array with the tourist
}
return 0;
}
Is it possible to have a map where the key is a string, and the value is an array of structures? And how can I append the array with new entries?
解决方案
- 地图:您可以使用 Tourist - 的字符串和向量的地图
map<string, std::vector<Tourist> > families;
。 - 插入:要向族中添加新元素,只需使用
push_back()
向量的方法 as -families[touristsList[i].surname].push_back(touristsList[i]);
。该语句将简单地将家庭(Tourist
结构)添加到带有姓氏键的地图中。
以下是您的程序的工作演示 -
#include <iostream>
#include<map>
#include<vector>
struct Tourist {
std::string name;
std::string surname;
std::string sex;
};
int getMinRoomsAmount(std::vector<Tourist> touristsList) {
std::map<std::string, std::vector<Tourist> > families;
for (int i=0; i < 3; i++) {
// to append the array with the tourist
families[touristsList[i].surname].push_back(touristsList[i]);
}
// iterating over the map and printing the Tourists families-wise
for(auto it:families){
std::cout<<"Family "<<it.first<<" : \n";
for(auto family : it.second){
std::cout<<family.name<<" "<<family.surname<<" "<<family.sex<<std::endl;
}
std::cout<<"\n-------\n";
}
return 0;
}
int main() {
// making 3 struct objects just for demo purpose
Tourist t1={"a1","b1","m"};
Tourist t2={"a2","b1","f"};
Tourist t3={"a3","b3","m"};
// inserting the objects into vector and then passing it to the function
std::vector<Tourist>t={t1,t2,t3};
getMinRoomsAmount(t);
}
我刚刚包含了 3 个旅游对象用于演示目的。您可以修改代码以满足您的需要。我使用了向量而不是数组,因为它们更有效,如果您想修改程序,您可以稍后根据用户输入动态推送/弹出。
希望这可以帮助 !
推荐阅读
- angular - angular cli ng generate 组件忽略了 angular.json 的默认值
- sharepoint - 使用基于 XML 的查询语言进行 SharePoint 列表连接的数据驱动 SSRS 订阅
- python-3.x - 我在 csv 文件中读取了一行,想知道一个单词的项目编号
- excel - 当用户输入是日期时,如何编码“下个月的第一个星期一”?
- java - java ee的灵活认证解决方案
- angular - 响应重定向(302)在角度不起作用
- javascript - 拖放适用于 IE 和边缘,但不适用于 chrome 或 firefox
- python - 如何修复未在 vscode 中加载但在 IDLE python 中加载的 dll
- java - 为什么我必须给父母创建客户?
- spring-data-jpa - 为同一数据库列创建可变参数@Query