stl关联容器
总共有8个关联容器,体现在三个不同的纬度上: 1)是一个map,还是一个set 2)是否允许重复的关键字 3)是否需要按照顺序保存
使用关联容器
map <string ,size_t> word_count;
string word;
while (cin >>word)
++word_count[word];
for (const auto &w : word_count)
cout <<w.first<<" occurs " <<w.second
<< ((w.second > 1 )?"times" :"time" ) <<endl;
使用下标运算符时,如果不存在,则创建一个新的元素,值初始化
map <string ,size_t> word_count;
set <string > excludes = {"The" ,"But" ,"And" ,"Or" ,"An" ,"A" };
string word;
while (cin >>word)
if (excludes.find(word) == exclude.end())
++word_count[word];
定义关联容器
map <string ,size_t> word_count;
set <string > excludes = {"The" ,"But" ,"And" ,"Or" ,"An" ,"A" };
map <string ,string > authors = {{"Joyce" ,"James" }};
关键字类型的限制
“行为正常”的<运算符的要求
两个关键字不能够同时“小于等于”对方 如果k1“小于等于”k2,且k2“小于等于”k3,则k1“小于等于”k3 如果两个关键字均不“小于等于”对方,则两者等价 比较操作也是容器类型的一部分
multiset <Sales_data,decltype (compareIsbn)*> bookstore(compareIsbn);
pair类型
pair < T1,T2> p;
pair < T1,T2> p(v1,v2);
pair < T1,T2> p = {v1,v2};
make_pair(v1,v2);
关联容器操作
pair的关键字是const的,我们可以改变pair的值,但是无法改变关键字成员的值
auto map_it = word_count. begin();
cout<< map_it-> first;
cout<< " " << map_it-> second;
map_it-> first = "new key" ;
++ map_it-> second;
遍历迭代器
auto map_it = word_count.cbegin();
while (map_it!=word_count.cend ()) {
cout <<map_it -> first<<" occurs " <<map_it->second <<" times " <<endl;
++map_it;
}
添加元素
map <string ,size_t> word_count;
string word;
while (cin >>word){
auto ret = word_count.insert({word,1 });
if (!ret.second)
++ret.first->second;
}
如果是multimap类型,insert函数返回是指向新元素的迭代器 ,无需返回bool值
删除元素
有三种erase方法可以调用
c.erase(k) 从c中删除每个关键字为k的元素。返回一个size_type值,指出删除元素的数量 c.erase(p) 从c中删除迭代器p指向的元素 c.erase(b,e) 从c中删除迭代器对b和e所表示的范围中的元素。返回e
map的下表操作
下标 VS at
c[k] 返回关键字为k的元素;如果k不在c中,添加一个关键字为k的元素,对其进行值初始化 c.at(k) 若k不在c中,抛出一个out_of_range 异常
访问元素
find / count 对于有序容器来说,lower_bound / upper_bound 在mutlimap和multiset中查找元素
string search_item("Alain de Botton" );
auto entries = authors.count (search_item);
auto iter = authors.find(search_item);
while (entries){
cout<<iter->second <<endl;
++iter;
}
for (auto pos = c.equal_range(search_item);pos .first!=pos .second;++pos .first)
cout<<pos .first->second<<endl;
无序容器
无序容器对关键字类型的要求
haser函数 == 运算符