如何制作一个地图,其中的值是C++中的结构数组
How can I make a map where the value is an array of structs in C++
我有以下结构。
struct Tourist {
string name;
string surname;
string sex;
};
我想按家庭对游客进行分类。
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;
}
是否有可能有一个映射,其中键是字符串,值是结构数组? 以及如何在数组中附加新条目?
-
地图:您可以使用 Tourist -
map<string, std::vector<Tourist> > families;
的字符串和矢量地图。 -
插入 :要向族添加新元素,只需使用
push_back()
向量方法作为 -families[touristsList[i].surname].push_back(touristsList[i]);
。此语句将简单地将 family(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 个旅游对象用于演示目的。您可以修改代码以满足您的需求。我使用了向量而不是数组,因为它们更有效,如果您想修改程序,您可以稍后根据用户输入动态推送/弹出。
希望这有帮助!
你真的想远离数组,尤其是在使用std::map
时。std::map
将复制您的结构,并且数组不能很好地复制。
下面是一个映射的定义,其值为 std::vector:
std::map<std::string, std::vector<Tourist>>
以下是添加到地图的方法:
std::vector<Tourist> database;
Tourist t1{"x", "x", "x"};
Tourist t2{"y", "y", "y"};
Tourist t3{"z", "z", "z"};
database.pushback(t1);
database.pushback(t2);
database.pushback(t3);
// Check this out:
std::map<std::string, std::vector<Tourist>> visitors;
visitor["Italy"] = database;
使用字符串映射→vector<Tourist>
.
然后以正常方式使用向量,例如push_back
.
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '