一、
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实现。
以前我们是这样打印信息出来的:
- static inline const char *
- VNET_TYPE_STRING(vnet_type_t type)
- {
- static VALUE_STRING_STRUCT g_type_string[] =
- {
- { VNET_TYPE_UNKOWN, "unkown1" },
- { VNET_TYPE_SOCKET, "socket" },
- { VNET_TYPE_RDP, "rdp" },
- { VNET_TYPE_PCOIP, "pcoip" },
- { VNET_TYPE_ICA, "ica" },
- { VNET_TYPE_XRED, "xred" },
- { 0, NULL },
- };
- return GetValueString(g_type_string, (ULONG)type);
- }
- static inline const TCHAR *
- GetValueString(VALUE_STRING_STRUCT *vsarray, ULONG value)
- {
- VALUE_STRING_STRUCT *tmp = vsarray;
- while ( tmp->string != NULL )
- {
- if ( tmp->value == value )
- {
- return tmp->string;
- }
- tmp++;
- }
- return _T("unkown");
- }
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:
- #include <map>
- #include <iostream>
- using namespace std;
- int main( )
- {
- map <int, int> m1, m2, m3;
- map <int, int>::iterator m1_Iter;
- m1.insert ( pair <int, int> ( 1, 10 ) );
- m1.insert ( pair <int, int> ( 2, 20 ) );
- m1.insert ( pair <int, int> ( 3, 30 ) );
- m2.insert ( pair <int, int> ( 10, 100 ) );
- m2.insert ( pair <int, int> ( 20, 200 ) );
- m3.insert ( pair <int, int> ( 30, 300 ) );
- cout << "The original map m1 is:";