如何在c ++中从字符串转换为枚举值?

时间:2017-07-29 12:49:10

标签: c++ enums

我有这样的枚举

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

我试图通过传递字符串值来获取枚举的索引值。

例如,GetenumIndex("Mon")将返回0

该功能的原型如下:

week GetenumIndex(string )

C ++中实现这种转换函数的惯用方法是什么?

1 个答案:

答案 0 :(得分:0)

好的,你走了:

#include <iostream>
#include <string>
#include <map>
#include <exception>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

week GetenumIndex( const std::string s ) {    
    static std::map<std::string,week> string2week {
       { "Mon", Mon }, 
       { "Tue", Tue },
       { "Wed", Wed }, 
       { "Thur", Thur },
       { "Fri", Fri },
       { "Sat", Sat }, 
       { "Sun", Sun }   
    };
    auto x = string2week.find(s);
    if(x != std::end(string2week)) {
        return x->second;
    }
    throw std::invalid_argument("s");
}

int main() {
    week w = GetenumIndex("Thur");
    std::cout << w << std::endl;
}

直播here