码迷,mamicode.com
首页 > 编程语言 > 详细

C++primer 11.3.5节练习

时间:2017-08-22 23:15:08      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:ace   题目   ios   bsp   cin   count   space   span   primer   

练习11.27

对于multimap来说统计关键字出现的次数用count会很好,而对于map来说寻找关键字来说更加妥当;

练习11.28

 1 #include <iostream>
 2 #include <string>
 3 #include <set>
 4 #include <map>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <algorithm>
 8 #include <iterator>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     vector<int> vec = { 1,2,3,4,5 };
15     vector<int> vec2 = { 6,7,8,9,10 };
16     string s = "T";
17     string s1 = "B";
18     map<string, vector<int>> m = { { s,vec },{ s1,vec2 } };
19     auto it = m.find("T");
20     cout << (*it).first << " ";
21     for (auto &i : (*it).second)
22         cout << i << " ";
23     cout << endl;
24         system("pause");
25     return 0;
26 }

练习11.29

upper_bound:会指向所查找元素不影响排序的插入位置迭代器;

lower_bound:同上

equal_range:一个迭代器pair,两个迭代器都指向元素应该插入的位置

练习11.30

pos是一个迭代器pair,两个迭代器分别是指向查找元素第一个位置和指向查找元素最后一个元素之后的位置,pos.first指的是其第一个迭代器,解引用后是关键字,在调用second就是关键字对应的值;

练习11.31

 1 #include <iostream>
 2 #include <string>
 3 #include <set>
 4 #include <map>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <algorithm>
 8 #include <iterator>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     multimap<string, string> authors;
15     string str, str1;
16     string book{"asd"};
17     while (cin >> str >> str1)
18     {
19         authors.insert({ str, str1 });
20     }
21     authors.erase(book);
22     for (auto c : authors)
23     {
24         cout << c.first << " " << c.second << endl;
25     }
26     system("pause");
27     return 0;
28 }

加一种方法,题目非要使用find函数

 1 #include <iostream>
 2 #include <string>
 3 #include <set>
 4 #include <map>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <algorithm>
 8 #include <iterator>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     multimap<string, string> authors;
15     string str, str1;
16     string book("asd");
17     while (cin >> str >> str1)
18     {
19         authors.insert({ str, str1 });
20     }
21     auto it = authors.find(book);
22     for (; (*it).first == book;)
23         it = authors.erase(it);        //注意这里erase返回的类型
24     for (auto c : authors)
25     {
26         cout << c.first << " " << c.second << endl;
27     }
28     system("pause");
29     return 0;
30 }

 

练习11.32

见上

 

C++primer 11.3.5节练习

标签:ace   题目   ios   bsp   cin   count   space   span   primer   

原文地址:http://www.cnblogs.com/wuyinfenghappy/p/7413934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!