Map封装,方便以后直接调用
MyMap.h
<pre name="code" class="cpp">//#ifdef MYMAP_H
//#define MYMAP_H
#include <map>
#include <string>
#include <stdio.h>
using namespace std;
class MyMapClass
{
public:
//构造函数
MyMapClass();
//析构函数
~MyMapClass();
//设置数据
bool SetMapData(string key, int value);
bool SetMapData(int key,string value);
//获取数据
int GetMapDate(string key);
string GetMapDate(int key);
//删除数据
bool DeleteMapDate(string key);
bool DeleteMapDate(int key);
void PrintMap();//打印Map信息
private:
map<string,int> MapString; //[string] = int
map<int,string>MapInt;
int MapStringMaxSize;//限制string型容量大小
int MapIntMaxSize; //限制int型容量大小
};
//#endif
MyMap.cpp
<pre name="code" class="cpp">#include "stdafx.h"
#include "MyMap.h"
MyMapClass::MyMapClass()
{
MapIntMaxSize = 10;
MapIntMaxSize = 500;
}
MyMapClass::~MyMapClass()
{
if(!MapInt.empty())
{
for (map<int,string>::iterator iter = MapInt.begin();iter != MapInt.end();iter ++)
{
MapInt.erase(iter);
}
MapInt.clear();
}
if (!MapString.empty())
{
for (map<string,int>::iterator iter = MapString.begin();iter != MapString.end(); iter ++)
{
MapString.erase(iter);
}
MapString.clear();
}
}
bool MyMapClass::SetMapData(string key, int value)
{
map<string,int>::iterator iter;
iter = MapString.find(key);
if(iter != MapString.end())
{
iter->second = value;
return true;
}
int size = MapString.size();
if (size > MapStringMaxSize)
{
return false;
}
MapString.insert(pair<string,int>(key,value));
return true;
}
bool MyMapClass::SetMapData(int key, string value)
{
map<int,string>::iterator iter;
iter = MapInt.find(key);
if(iter != MapInt.end())
{
MapInt.erase(key);
}
else
{
int size = MapInt.size();
if (size > MapIntMaxSize)
{
return false;
}
}
MapInt.insert(pair<int,string>(key,value));
return true;
}
int MyMapClass::GetMapDate(string key)
{
map<string,int>::iterator iter;
iter = MapString.find(key);
if(iter == MapString.end())
{
return 0 ;
}
return iter->second;
}
string MyMapClass::GetMapDate(int key)
{
map<int,string>::iterator iter;
iter = MapInt.find(key);
if (iter == MapInt.end())
{
return NULL;
}
return iter->second;
}
bool MyMapClass::DeleteMapDate(string key)
{
map<string,int>::iterator iter;
iter = MapString.find(key);
if (iter == MapString.end())
{
return false;
}
MapString.erase(iter);
return true;
}
bool MyMapClass::DeleteMapDate(int key)
{
map<int,string>::iterator iter;
iter = MapInt.find(key);
if (iter == MapInt.end())
{
return false;
}
MapInt.erase(iter);
return true;
}
void MyMapClass::PrintMap()
{
if (!MapString.empty())
{
for (map<string,int>::iterator iter = MapString.begin();iter != MapString.end();iter ++)
{
printf("MapString first:%s,second:%d\n",iter->first.c_str(),iter->second);
}
}
if (!MapInt.empty())
{
for(map<int,string>::iterator iter = MapInt.begin();iter != MapInt.end();iter ++)
{
printf("MapInt first:%d,second:%s",iter->first,iter->second.c_str());
}
}
}