1. 程式人生 > >2018.11.1——11.2關聯容器概述_11.3關聯容器操作

2018.11.1——11.2關聯容器概述_11.3關聯容器操作

11.12

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>

using namespace std;

int main(int argc, char *argv[])
{
	vector<string> s = {"hello", "world", "!"};
	vector<int> number = {1, 2, 3);
	pair<stirng, int> p;
	vector<pair> vp;
	for(auto &I : s.size())
	{
		p.first.push_back(s[i]);
		p.second.push_back(number[i]);
		vp.push_back(p);
	}
	return 0;
}

答案

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
	ifstream in(argv[1]);
	if (!in)
	{
		cerr << "error" << endl;
		exit(1);
	}
	vector<pair<string, int>> data;
	string s;
	int v;
 	while(in >> s && in>> v)
 		data.push_back(pair<string, int>(s, v));
 	
 	for (auto &d : data)
 		cout << d.first << " " << d.second << endl;
 	return 0;
 }

第二種方法 將while迴圈體改為

data.push_back(make_pair(s, v));

第三種 改為

data.push_back({s,v});

11.14

void add_family(map<string, vector<pair<string, string>>> &families, const string &family)
{
	families[family];
}
void add_child(map<string, vector<pair<string, string>>> &families, const string &family, const string &child, const string &birthday)
{
	families[family].push_back(make_pair(child, birthday));
}

11.15