这个问题很可能是"如何将字符串映射到枚举"的第n次迭代.
我的要求更进一步,throw当在有效输入范围内找不到密钥时,我想要一个例外.所以我有这个实现EnumMap(需要提升const std::map定义):
#include <map>
#include <string>
#include <sstream>
#include <stdexcept>
#include <boost/assign.hpp>
typedef enum colors {
RED,
GREEN,
} colors;
// boost::assign::map_list_of
const std::map<std::string,int> colorsMap = boost::assign::map_list_of
("red", RED)
("green", GREEN);
//-----------------------------------------------------------------------------
// wrapper for a map std::string --> enum
class EnumMap {
private:
std::map<std::string,int> m_map;
// print the map to a string
std::string toString() const {
std::string ostr;
for(auto x : m_map) {
ostr += x.first + ", ";
} …Run Code Online (Sandbox Code Playgroud)