第十一章 11.2.3节练习

练习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;
}
代码里面没有输入正确性的检查,也就是鲁棒性比较低,需要按照约定好的格式进行输入才能正确显示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值