Map封装,方便以后直接调用

来源:互联网 发布:苏州plc编程培训 编辑:程序博客网 时间:2024/05/16 10:39

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] = intmap<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());}}}


0 0