C++primer学习:关联容器(3)
2015-10-10 21:29
387 查看
find操作
(1)find(k),返回一个迭代器,指向第一个关键字为k的元素.
(2)count(k),返回返回键字为k的元素的数量
(3)lower_bound(k)返回一个迭代器,指向第一个关键字不小于k的元素.
(4)upper_bound(k)返回一个迭代器,指向第一个关键字大于k的元素.
(5)equal_range(k),返回一个迭代器pair,表示关键字等于k的范围.如果k不存在,pair的两个成员均等于end();
===================================================================
定义一个string到int的vector的map并初始化,用一个变量存储find的结果:
map<string, vector<int >> word_count = { { "hello", vector<int>{1,2,3,4,5} } }; auto it = word_count.find("hello"); cout << (*it).second[1]; string word,name;
===================================================================
练习:编写一个multimap,用来存储作者与它的作品.输入想要删除的元素,确保该元素不在map也可以运行.
multimap<string, string>authors{ { "X", "SUV" }, { "pyb", "world" }, { "lwj", "The introduction" }, { "XXX", "hello" }, { "lwj", "C++" }, { "D", "CPP-Concurrency" } }; cout << "plz input name: "; string word; cin >>word; size_t count = authors.count(word); auto pos = authors.find(word); while (count--) authors.erase(pos++); for (const auto& author : authors) cout << author.first << " " << author.second << std::endl; return 0; }
使用上一题的map,按字典顺序打印作者和他的作品
基本思路:将作者的作品重新插入到一个set中,因为这样可以保证作品按字典顺序排列.否则就需要用到sort函数.
multimap<string, string>authors{ { "pyb", "SUV" }, { "pyb", "world" }, { "lwj", "The introduction" }, { "XXX", "hello" }, { "lwj", "C++" }, { "XXX", "CPP-Concurrency" } }; map<string, multiset<string>> ordered_authors; for (const auto & it : authors) ordered_authors[it.first].insert(it.second); for (const auto &it : ordered_authors) { cout <<endl<< it.first << ":\n"; for (const auto &book : it.second) cout << book << " "; } return 0;
相关文章推荐
- B树算法与实现 (C语言实现)
- 重学C++Primer笔记6---指针、typedef、const、define彻底理解
- C++---if(!cin)与if(!(cin >> xxx))
- 字符转二进制_C++实现(续)
- C++Primer第五版 练习11.31-32(解答)
- C++Primer第五版 练习11.28(解答)
- C++Primer第五版 11.3.5节练习
- C++继承
- C++学习笔记16——成员函数
- C++学习笔记15——局部对象与内联函数
- C++学习笔记14——默认实参
- C++学习笔记13——函数返回值
- C++学习笔记12——函数的参数传递
- C++学习笔记11——动态数组与多维数组
- C++学习笔记10——指针
- C++学习笔记9——数组
- C++学习笔记8——迭代器(iterator)
- 栈的顺序存储方式的C语言实现
- C++基础语法注意细节
- .h和.c和.cpp多文件包含时候发生的多重定义错误问题(转载)