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

C++primer 10.4.1节练习

练习10.26

back_inserter创建一个使用push_back的迭代器。 
front_inserter创建一个push_front的迭代器。 
Inserter创建一个使用insert的迭代器。此函数接收第二个参数,这个参数必须是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前。

 

练习10.27

 1 #include<iostream>
 2 #include<string>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include <algorithm>
 7 #include <list>
 8 #include <functional>
 9 #include <iterator>
10 using namespace std;
11 using namespace placeholders;
12 
13 void elmDups(vector<string> &vec, list<string> &);
14 
15 int main()
16 {
17     vector<string> words{ "the", "quick", "red", "fox", "jumps", "over","the", "slow","red","turtle" };
18     list<string> li;
19     elmDups(words, li);
20     for (auto c : li)
21         cout << c << endl;
22     system("pause");
23     return 0;
24 }
25 
26 void elmDups(vector<string>& vec, list<string> &li)
27 {
28     sort(vec.begin(), vec.end());
29     unique_copy(vec.begin(), vec.end(), back_inserter(li));
30 }

练习10.28

 1 #include <iostream>
 2 #include <vector>
 3 #include <list> 
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     vector<int> vec;
11     list<int> vec2 = {10,11,12},vec3 = {10,11,12},vec4 = {10,11,12};
12     for(int i = 1; i <= 9; ++i)
13         vec.push_back(i);
14 
15     copy(vec.cbegin(), vec.cend(), front_inserter(vec2));
16     for(auto it = vec2.begin(); it != vec2.end(); ++it)
17         cout << *it << " ";
18         cout << endl;
19 
20     copy(vec.cbegin(), vec.cend(), back_inserter(vec3));
21     for(auto it = vec3.begin(); it != vec3.end(); ++it)
22         cout << *it << " ";
23         cout << endl;
24 
25     copy(vec.cbegin(), vec.cend(), inserter(vec4,vec4.begin()));
26     for(auto it = vec4.begin(); it != vec4.end(); ++it)
27         cout << *it << " ";
28         cout << endl;
29     return 0;
30 }

 

C++primer 10.4.1节练习