关联容器按关键字来保存和访问。
无序容器使用哈希函数来组织元素。
#map,set,单词计数器
map<string, int> word_count;
set<string> exclude = {"and", "the"};
string word;
while(cin >> word)
if(exclude.find(word) == exclude.end()) //迭代器
++word_count[word];
for(const auto &w : word_count) //c++11
cout << w.first << " occurs " << w.second
<< ((w.second > 1) ? " times " : " time ") << endl;
return 0;
解引用关联容器的迭代器,得到的是容器的value_type,这是一个pair
auto m = word_count.begin();
cout << m->first << " " << m->second << endl;
m->second = 100;
cout << m->first << " " << m->second << endl;
遍历关联容器(迭代器)
auto m = word_count.begin();
while(m != word_count.end()){
cout << m->first << " occurs " << m->second
<< ((m->second > 1) ? " times " : " time ") << endl;
m++;
}
添加元素,插入
word_count.insert({"novak", 8}); //最简单
word_count.insert(make_pair("novak", 8));
word_count.insert(pair<string, size_t>("novak", 8));
word_count.insert(map<string, size_t>::value_type("novak", 8));
相关操作
c.insert(v)
c.emplace(args) //args用来构造元素,返回一个pair,包含一个指向关键字的迭代器,以及一个是否插入成功的bool
c.insert(b, e) //b和e是c::value_type的迭代器范围
c.insert(il) //il是花括号列表
删除
c.erase(k) //删除关键字为k的元素,返回删除元素个数
c.erase(p) //c中删除迭代器p指定的元素,返回p的下一迭代器
c.erase(b, e) //删除迭代器范围的元素,返回e
map的下标操作
若关键字不在map中,会创建一个元素插入到map中,关联值将其初始化。比insert简洁了。
访问元素
根据情况选择find或者count
c.find(k) //返回指向第一个关键字为k的迭代器,没找到,返回末尾迭代器
c.count(k) //返回关键字为k的元素的数量
find不会插入不存在的元素
在multimap或multiset中查找所有元素
string name("Novak");
auto nums = authors.count(name);
auto iter = authors.find(name);
while(nums){
cout << iter->second << endl;
++iter;
--nums;
}
可以使用c.equal_range(k)函数解决上述问题。
for(auto pos = authors.equal_range(name); pos.first != pos.second; ++pos.first)
cout << pos.first->second << endl;