i007.cc

i007.cc

优先队列-降维打击

关于Multimap的遍历和删除

关于Multimap的遍历和删除

 2046人阅读 评论(0) 收藏 举报
 分类:

C++的STL的关联容器multimap允许一个key值对应多个值,当对整个multimap进行遍历时可以使用迭代器,迭代器会指向多个键值对,而不是一个键值后的多个值,当希望输出key:value1 value2…形式时,需要使用count函数计算一个key值包含多少个值,然后使用循环对迭代器自增输出这些值。

当需要删除多个值中的某一个时,使用equal_range函数保存某一key值对应所有值的起始位置,这两个位置保存在一个pair对中,用first值遍历这些值,找到符合条件的删除,否则自增,由于删除操作会使迭代器失效,故将erase函数的返回值赋值给first迭代器,令其指向删除元素的下一个元素,保证first迭代器不会失效。

[cpp] view plain copy

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5. int main ()
  6. {
  7.     multimap<string,int> authors;
  8.     for (int i=0;i<10;i++)//初始化一个multimap
  9.     {
  10.         for (int j=0;j<=i;j++)
  11.         {
  12.             string s;
  13.             s+=‘a’+j;
  14.             authors.insert(make_pair(s,i));
  15.             authors.insert(make_pair(s,i-1));
  16.         }
  17.     }
  18.     multimap<string,int>::iterator map_it=authors.begin();
  19.     typedef multimap<string,int>::iterator authors_it;
  20.     cout<<“原multimap容器:”<<endl;
  21.     while (map_it!=authors.end())//遍历multimap容器,由于map_it一次指向包含一个键值对,例如,当前map_it指向(a,0),自增之后指向(a,1)
  22.                      //故仅在第一次输出first值,使用count函数计算该键对应的值个数,然后循环输出各second值,同时增加map_it
  23.     {
  24.         cout<<map_it->first<<“:”;
  25.         typedef multimap<string,int>::size_type sz_type;//multimap数量类型
  26.         sz_type cnt=authors.count(map_it->first);//返回一个键对应的值个数
  27.         for (sz_type i=0;i!=cnt;++map_it,++i)//循环输出各值,同时自增map_it
  28.         {
  29.             cout<<map_it->second<<” “;
  30.         }
  31.         cout<<endl;
  32.     }
  33.     map_it=authors.find(“c”);//删除(c,5)
  34.     pair<authors_it,authors_it> pos=authors.equal_range(map_it->first);//利用一对multimap<string,int>指向第一个出现(c,5)的位置和最后一个出现(c,5)的位置
  35.     while (pos.first!=pos.second)
  36.     {
  37.         if (pos.first->second==5)//当pos指向5时
  38.         {
  39.             pos.first=authors.erase(pos.first);//删除后会改变pos迭代器,故赋值给自身,指向删除后的下一个键值对
  40.         }
  41.         else
  42.             ++pos.first;//不进行删除操作则自增
  43.     }
  44.     cout<<“删除(c,5)之后的multimap容器:”<<endl;//输出删除(c,5)之后的multimap
  45.     map_it=authors.begin();
  46.     while (map_it!=authors.end())//遍历multimap容器,由于map_it一次指向包含一个键值对,例如,当前map_it指向(a,0),自增之后指向(a,1)
  47.                      //故仅在第一次输出first值,使用count函数计算该键对应的值个数,然后循环输出各second值,同时增加map_it
  48.     {
  49.         cout<<map_it->first<<“:”;
  50.         typedef multimap<string,int>::size_type sz_type;//multimap数量类型
  51.         sz_type cnt=authors.count(map_it->first);//返回一个键对应的值个数
  52.         for (sz_type i=0;i!=cnt;++map_it,++i)//循环输出各值,同时自增map_it
  53.         {
  54.             cout<<map_it->second<<” “;
  55.         }
  56.         cout<<endl;
  57.     }
  58.     system(“pause”);
  59.     return 0;
  60. }

发表回复