首页 > 解决方案 > 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?

标签: c++

解决方案


  • 地图:您可以使用 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 个旅游对象用于演示目的。您可以修改代码以满足您的需要。我使用了向量而不是数组,因为它们更有效,如果您想修改程序,您可以稍后根据用户输入动态推送/弹出。

希望这可以帮助 !


推荐阅读