您的位置:首页 > 编程语言 > C语言/C++

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: