首页 > 代码库 > C++primer 9.2.4节练习

C++primer 9.2.4节练习

练习9.11

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     string example("Testing!");
10 
11     vector<string> vec1;     
12     vec1.push_back(example);
13 
14     vector<string> vec2(vec1);
15 
16     vector<string> vec3 = vec2;
17 
18     vector<string> vec4{"This","is","a","testing!"};
19 
20     vector<string> vec5={"This","is","a","testing!"};
21 
22     auto iter1 = vec5.begin();
23     auto iter2 = vec5.end();
24     vector<string> vec6(iter1,iter2);
25 
26     for(auto i = 0; i!= vec1.size(); ++i)
27         cout << vec1[0] << endl;
28 
29      for(auto i = 0; i != vec2.size(); ++i)
30         cout << vec2[0] << endl;
31 
32     for(auto i = 0; i != vec3.size(); ++i)
33         cout << vec3[0] << " ";
34         cout << endl;
35 
36     for(auto i = 0; i != vec4.size(); ++i)
37         cout << vec4[i] << " ";
38         cout << endl;
39 
40     for(auto i = 0; i != vec5.size(); ++i)
41         cout << vec5[i] << " ";
42         cout << endl;
43 
44     for(auto i = 0; i != vec6.size(); ++i)
45         cout << vec6[i] << " ";
46         cout << endl;
47     return 0;
48 }

练习9.12

接受两个迭代器的拷贝构造函数可以将一个容器内的子序列进行拷贝,而接收一个容器创建其拷贝的构造函数拷贝的是整个容器所有的元素。

而且为了创建一个容器为另外一个容器的拷贝,两个容器的类型及其元素类型必须匹配,当传递迭代器参数来拷贝一个范围时,就不要求容器类型是相同的了,新容器和原容器中的元素类型也可以不同,只要能将拷贝的元素转换为要初始化的容器的元素类型即可;

练习9.13

 1 #include <iostream>
 2 #include <fstream>
 3 #include <sstream>
 4 #include <vector>
 5 #include <list>
 6 #include <iterator>
 7 
 8 using namespace std;
 9 
10 int main()
11 {
12     list<int> li{ 1,2,3,4,5,6 };
13     vector<int> li1{ 10,9,8,7,6,5 };
14     vector<int>::iterator it = li1.begin();
15     vector<int>::iterator it1 = li1.end();
16     vector<double> num0(it, it1);
17     vector<double> num(li.begin(), li.end());
18     for (auto c : num0)
19         cout << c << " ";
20     for (auto c : num)
21         cout << c << endl;
22     system("pause");
23     return 0;
24 }

 

C++primer 9.2.4节练习