练习11.12
编写程序,读入string和int的序列,将每个string和int存入一个pair中,pair保存在一个vector中。
解答:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main(){
vector<pair<string, int>> vec;
string words[] = { "apple", "pear", "melon", "hello", "world", "google", "baidu" };
int nums[] = { 1, 2, 3, 4, 5, 6, 7};
auto sfirst = begin(words);
auto slast = end(words);
auto nfirst = begin(nums);
auto nlast = end(nums);
auto nit = nfirst;
auto sit = sfirst;
for (; nit != nlast && sit !=slast ; ++sit, ++nit){
pair<string, int> p(*sit, *nit);
vec.push_back(p);
}
for (auto i : vec){
cout << i.first << "=>" << i.second << endl;
}
return 0;
}
练习11.13
在上一题的程序中,至少有三种创建pair的方法。编写此程序的三个版本,分别采用不同的方法创建pair。
解释你认为哪种形式最易于编写和理解,为什么?
解答:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
#define N 3
int main(){
vector<pair<string, int>> vec;
string words[] = { "apple", "pear", "melon", "hello", "world", "google", "baidu" };
int nums[] = { 1, 2, 3, 4, 5, 6, 7};
auto sfirst = begin(words);
auto slast = end(words);
auto nfirst = begin(nums);
auto nlast = end(nums);
auto nit = nfirst;
auto sit = sfirst;
#if N == 1
for (; nit != nlast && sit !=slast ; ++sit, ++nit){
pair<string, int> p(*sit, *nit);
vec.push_back(p);
}
#elif N == 2
for (; nit != nlast && sit !=slast ; ++sit, ++nit){
pair<string, int> p = { *sit, *nit };
vec.push_back(p);
}
#elif N == 3
for (; nit != nlast && sit != slast; ++sit, ++nit){
vec.push_back(make_pair(*sit, *nit));
}
#endif
for (auto i : vec){
cout << i.first << "=>" << i.second << endl;
}
return 0;
}
我感觉第三终易与编写,简单明确,不过要求对添加的元素类型比较清楚,否则容易出错。
第一种易与理解,可以明确的知道pair中的类型是否和vec中的元素一致。
练习11.14
扩展你在11.2.1节练习(第378页)中编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名和生日。
解答:
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main(){
map<string, vector<pair<string, string>>> families;
string family_name, giving_name, birthday;
while (cin >> giving_name){
cin >> family_name;
cin >> birthday;
families[family_name].push_back(make_pair(giving_name, birthday));
}
for (map<string, vector<pair<string, string>>>::iterator it = families.begin();
it != families.end(); ++it){
cout << "The family name is "<<it->first << " " << endl;
for (const auto &i : it->second){
cout << "\t" << i.first << "'s birthday is " << i.second << endl;
}
cout << endl;
}
return 0;
}
代码里面没有输入正确性的检查,也就是鲁棒性比较低,需要按照约定好的格式进行输入才能正确显示。