11.2.3节练习

练习11.12 编写程序,读入string和int的序列,将每string和int存入一个pair中,保存在一个vector中。

#include <iostream>
#include <vector>
#include <utility>
#include <string>
using namespace std;
int main()
{
	pair<string, int> pair_si;
	vector<pair<string, int>> pair_vec;
	string s;
	int i;
	while (cin >> s >> i) {
		pair_si = { s,i };
		pair_vec.push_back(pair_si);
	}
	for (auto &c : pair_vec) {
		cout << c.first << " " << c.second << endl;
	}
	return 0;

}

练习11.13 在上一题的程序中,至少有三种创建pair的方法。编写次程序的三个版本,分别采用不同的方法创建pair。解释你认为哪种形式最易于编写和理解,为什么?

#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main()
{
	pair<string, int> pair_si;
	vector<pair<string, int>> pair_vec;
	string s;
	int i;
	while (cin >> s >> i) {
		pair_si = { s,i };         //最简洁。
		pair_vec.push_back(pair_si);
		
		pair<string, int>pair_si(s, i); 
		pair_vec.push_back(pair_si);
		
		pair_si = make_pair(s, i);    // 这个排第一, 在大程序中 应该最清晰,指出返回pair类型。
		pair_vec.push_back(pair_si);

		pair_si.first = s;
		pair_si.second = i;
		pair_vec.push_back(pair_si);
	}
	for (auto &c : pair_vec) {
		cout << c.first << " " << c.second << endl;
	}
	return 0;
}

练习11.14 扩展你在11.2.1节练习(第378页)中编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名字和生日。

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
using namespace std;
int main()
{
	map<string, vector<string>> name = {
		{ "Paul",{ "Pierce","Christ" } },
		{ "Green",{ "Jogre" } }
	};
	pair<string, int> child;
	vector<pair<string, int>> child_bir;
	
	string fir, sec;
	int bir;
	while (cin >> fir >> sec >> bir) {
		//利用Push_back往容器添加元素。
		name[fir].push_back(sec);
		// 将完整的名字及其生日保存到child
		child = { fir + " " +sec, bir };
		child_bir.push_back(child);
	}
	for (auto &i : child_bir) {
		cout << i.first << ": " << i.second << endl;
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值