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

#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;
}
原文地址:https://www.cnblogs.com/sggggr/p/13442533.html