11.2.1节练习
【练习11.7】代码:
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 #include<map> 5 using namespace std; 6 7 void add_family(map<string, vector<string>> &familes, const string &str) 8 { 9 if (familes.find(str) == familes.end()) //去掉这个判断不影响输出结果 10 familes[str]; // familes[str] = vector<string>(); 11 } 12 13 void add_child(map<string, vector<string>> &familes, const string &family, const string &child) 14 { 15 familes[family].push_back(child); 16 } 17 18 int main() 19 { 20 map<string, vector<string>> familes; 21 add_family(familes, "张"); 22 add_child(familes, "张", "强"); 23 add_child(familes, "张", "刚"); 24 add_child(familes, "王", "五"); 25 add_family(familes, "王"); 26 for (auto f : familes) 27 { 28 cout << f.first << " 家的孩子: "; 29 for (auto c : f.second) 30 cout << c << " "; 31 cout << endl; 32 } 33 return 0; 34 }
运行结果: