Map与Multimap用法

 

一、

Map是c++的一个标准容器,它提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!
1. map构造函数;
map<string , int >mapstring; map<int ,string >mapint;
map<sring, char>mapstring; map< char ,string>mapchar;
map<char ,int>mapchar; map<int ,char >mapint;

如在打枚举中打印 “指定值对应的字符串”时,可是采用map<int, string>的STL实现。

以前我们是这样打印信息出来的:

[cpp]   view plain copy
  1. static inline const char *   
  2. VNET_TYPE_STRING(vnet_type_t type)  
  3. {  
  4.     static VALUE_STRING_STRUCT g_type_string[] =  
  5.     {  
  6.         { VNET_TYPE_UNKOWN, "unkown1" },  
  7.         { VNET_TYPE_SOCKET, "socket" },  
  8.         { VNET_TYPE_RDP,    "rdp" },  
  9.         { VNET_TYPE_PCOIP,  "pcoip" },  
  10.         { VNET_TYPE_ICA, "ica" },  
  11.         { VNET_TYPE_XRED, "xred" },  
  12.         { 0, NULL },  
  13.     };  
  14.     return GetValueString(g_type_string, (ULONG)type);  
  15. }  
[cpp]   view plain copy
  1. static inline const TCHAR *  
  2. GetValueString(VALUE_STRING_STRUCT *vsarray, ULONG value)  
  3. {  
  4.     VALUE_STRING_STRUCT *tmp = vsarray;  
  5.   
  6.     while ( tmp->string != NULL )  
  7.     {  
  8.         if ( tmp->value == value )  
  9.         {  
  10.             return tmp->string;  
  11.         }  
  12.         tmp++;  
  13.     }  
  14.     return _T("unkown");  
  15. }  



 

2. map添加数据;
map<int ,string> maplive; 
1.maplive.insert(pair<int,string>(102,"aclive"));
2.maplive.insert(map<int,string>::value_type(321,"hai"));
3, maplive[112]="April";//map中最简单最常用的插入添加!

3,map中元素的查找:

find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。

map<int ,string >::iterator l_it;; 
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else cout<<"wo find 112"<<endl;


4,map中元素的删除:
如果删除112;
map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else maplive.erase(l_it); //delete 112;

 


5,map中 swap的用法
Map中的swap不是一个容器中的元素交换,而是两个容器交换

For example:

[cpp]   view plain copy
  1. #include <map>  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6.   
  7. int main( )  
  8. {  
  9.     map <intint> m1, m2, m3;  
  10.     map <intint>::iterator m1_Iter;  
  11.   
  12.     m1.insert ( pair <intint> ( 1, 10 ) );  
  13.     m1.insert ( pair <intint> ( 2, 20 ) );  
  14.     m1.insert ( pair <intint> ( 3, 30 ) );  
  15.     m2.insert ( pair <intint> ( 10, 100 ) );  
  16.     m2.insert ( pair <intint> ( 20, 200 ) );  
  17.     m3.insert ( pair <intint> ( 30, 300 ) );  
  18.   
  19.     cout << "The original map m1 is:";  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值