[英]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;
}
是否可以有一個 map,其中鍵是字符串,值是結構數組? 我怎樣才能 append 具有新條目的數組?
map<string, std::vector<Tourist> > families;
.push_back()
方法families[touristsList[i].surname].push_back(touristsList[i]);
. 該語句將簡單地將家庭( Tourist
struct)添加到 map 與姓氏鍵。以下是您的程序的工作演示 -
#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 個旅游對象用於演示目的。 您可以修改代碼以滿足您的需要。 我使用了向量而不是數組,因為它們更有效,如果您想修改程序,您可以稍后根據用戶輸入動態推送/彈出。
希望這可以幫助 !
您真的想遠離 arrays,尤其是在使用std::map
時。 std::map
將復制您的結構,而 arrays 不能很好地復制。
這是一個 map 的定義,其值為 std::vector:
std::map<std::string, std::vector<Tourist>>
以下是添加到 map 的方法:
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>
的 map。
然后以正常方式使用向量,例如push_back
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.