如何将枚举数据直接转换成字符串


#include <iostream>
#include <string>
#include <map>
using namespace std;

enum MPType 
{
MPT_None,
MPT_Other,
MPT_Board,
MPT_Length
};

//方案一,直接用数组

string MPTypeString[MPT_Length] = {
"MPT_None",
"MPT_Other",
"MPT_Board"
};

方案二,用map

//方案二,用map
class MPTypeConverter {
public:
MPTypeConverter() {
map.insert(make_pair(MPT_None, "MPT_None"));
map.insert(make_pair(MPT_Other, "MPT_Other"));
map.insert(make_pair(MPT_Board, "MPT_Board"));
}

string ToString(MPType key) {
MPTypeStringMap::iterator pos = map.find(key);
if (pos != map.end())
return pos->second;
return string("");
}

private:
typedef map<MPType, string> MPTypeStringMap;
MPTypeStringMap map;
};

int main()
{
MPTypeConverter converter;
cout << MPTypeString[MPT_Board] << endl;
cout << converter.ToString(MPT_Board) << endl;
return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM