`
buerkai
  • 浏览: 166711 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

简单实现一个hashtable---------在cocos2d-x中存放全局变量

 
阅读更多

#include <map>
#include <iostream>

static std::map<std::string,std::string> datamap;

/*
*@description: 存入一个string类型的数据
*@author: buerkai.iteye.com
*@fullName: put
*@param1: key
*@param2: value
*/
static void put(std::string key,std::string value)
{
if(datamap.find(key)!=datamap.end()){
datamap.find(key)->second=value;
}else{
datamap.insert(make_pair(key,value));
}

}


/*
*@description: 取一个string类型的数据,没有返回为空串
*@author: buerkai.iteye.com
*@fullName: get
*@param1: key
*/
static std::string get(std::string key)
{
if(datamap.find(key)!=datamap.end()){
return datamap.find(key)->second;
}else{
return "";
}
}


/*
*@description: 删除string类型的数据
*@author: buerkai.iteye.com
*@fullName: deleteValue
*@param1: key
*/
static void deleteValue(std::string key){
if(datamap.find(key)!=datamap.end()){
datamap.erase(key);
}
}

/*
*@description: 存入一个Int类型的数据
*@author: buerkai.iteye.com
*@fullName: put
*@param1: key
*@param2: value
*/
static void putInt(std::string key,int value)
{
char tt[10];
put(key,itoa(value,tt,10));
}

/*
*@description: 取一个Int类型的数据,没有返回0
*@author: buerkai.iteye.com
*@fullName: getInt
*@param1: key
*/
static int getInt(std::string key)
{
std::string dd=get( key);
if(dd==""){
return 0;
}else{
return std::atoi(dd.c_str());
}
}

/*
*@description: 存入一个Float类型的数据
*@author: buerkai.iteye.com
*@fullName: putFloat
*@param1: key
*@param2: value
*/
static void putFloat(std::string key,float value)
{
char tmpstr[32];
memset(tmpstr,'\0',32);
    sprintf(tmpstr,"%f",value);
put(key,std::string(tmpstr));
}


/*
*@description: 取一个Float类型的数据,没有返回0.0f
*@author: buerkai.iteye.com
*@fullName: getFloat
*@param1: key
*/
static float getFloat(std::string key)
{
std::string dd=get( key);
if(dd==""){
return 0.0f;
}else{
return std::atof(dd.c_str());
}
}



/*
*@description: 存入一个bool类型的数据
*@author: buerkai.iteye.com
*@fullName: putBool
*@param1: key
*@param2: value
*/
static void putBool(std::string key,bool value)
{
std::string tt="0";
if(value)
{
tt="1";
}
put(key,std::string(tt));
}



/*
*@description: 取一个bool类型的数据,没有返回false
*@author: buerkai.iteye.com
*@fullName: getBool
*@param1: key
*/
static bool getBool(std::string key)
{
std::string dd=get( key);
if(dd==""||dd=="0"){
return 0;
}else if(dd=="1"){
return 1;
}
return 0;
}



前一段时间,在做小游戏的时候,将游戏的全局变量放在一个gamedata.h文件中,每次include这个文件的时候,里面定义的全局变量就重新初始化了,为了解决这个问题,简单模仿了一个JAVA中的hashtable。可以放在单列类中,存放游戏中的全局变量,以上函数已经过测试,放心使用吧。

转载请注明出处:http://buerkai.iteye.com

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics