关于Multimap的遍历和删除
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++的STL的关联容器multimap允许一个key值对应多个值,当对整个multimap进行遍历时可以使用迭代器,迭代器会指向多个键值对,而不是一个键值后的多个值,当希望输出key:value1 value2…形式时,需要使用count函数计算一个key值包含多少个值,然后使用循环对迭代器自增输出这些值。
当需要删除多个值中的某一个时,使用equal_range函数保存某一key值对应所有值的起始位置,这两个位置保存在一个pair对中,用first值遍历这些值,找到符合条件的删除,否则自增,由于删除操作会使迭代器失效,故将erase函数的返回值赋值给first迭代器,令其指向删除元素的下一个元素,保证first迭代器不会失效。
- #include <iostream>
- #include <map>
- #include <string>
- using namespace std;
- int main ()
- {
- multimap<string,int> authors;
- for (int i=0;i<10;i++)//初始化一个multimap
- {
- for (int j=0;j<=i;j++)
- {
- string s;
- s+=‘a’+j;
- authors.insert(make_pair(s,i));
- authors.insert(make_pair(s,i-1));
- }
- }
- multimap<string,int>::iterator map_it=authors.begin();
- typedef multimap<string,int>::iterator authors_it;
- cout<<“原multimap容器:”<<endl;
- while (map_it!=authors.end())//遍历multimap容器,由于map_it一次指向包含一个键值对,例如,当前map_it指向(a,0),自增之后指向(a,1)
- //故仅在第一次输出first值,使用count函数计算该键对应的值个数,然后循环输出各second值,同时增加map_it
- {
- cout<<map_it->first<<“:”;
- typedef multimap<string,int>::size_type sz_type;//multimap数量类型
- sz_type cnt=authors.count(map_it->first);//返回一个键对应的值个数
- for (sz_type i=0;i!=cnt;++map_it,++i)//循环输出各值,同时自增map_it
- {
- cout<<map_it->second<<” “;
- }
- cout<<endl;
- }
- map_it=authors.find(“c”);//删除(c,5)
- pair<authors_it,authors_it> pos=authors.equal_range(map_it->first);//利用一对multimap<string,int>指向第一个出现(c,5)的位置和最后一个出现(c,5)的位置
- while (pos.first!=pos.second)
- {
- if (pos.first->second==5)//当pos指向5时
- {
- pos.first=authors.erase(pos.first);//删除后会改变pos迭代器,故赋值给自身,指向删除后的下一个键值对
- }
- else
- ++pos.first;//不进行删除操作则自增
- }
- cout<<“删除(c,5)之后的multimap容器:”<<endl;//输出删除(c,5)之后的multimap
- map_it=authors.begin();
- while (map_it!=authors.end())//遍历multimap容器,由于map_it一次指向包含一个键值对,例如,当前map_it指向(a,0),自增之后指向(a,1)
- //故仅在第一次输出first值,使用count函数计算该键对应的值个数,然后循环输出各second值,同时增加map_it
- {
- cout<<map_it->first<<“:”;
- typedef multimap<string,int>::size_type sz_type;//multimap数量类型
- sz_type cnt=authors.count(map_it->first);//返回一个键对应的值个数
- for (sz_type i=0;i!=cnt;++map_it,++i)//循环输出各值,同时自增map_it
- {
- cout<<map_it->second<<” “;
- }
- cout<<endl;
- }
- system(“pause”);
- return 0;
- }
