如何制作一个地图,其中的值是C++中的结构数组

How can I make a map where the value is an array of structs in C++

本文关键字:C++ 数组 结构 何制作 地图 一个      更新时间:2023-10-16

我有以下结构。

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.