2014-11-20 174 views
-1

我知道这个问题已经在这里已经回答:C++ string to enum 但我真的失去了如何使用它,请不要鲁莽;)字符串到枚举C++

我想我的字符串转换在tEnumCouleur .. 我:

#pragma once 
    #include <map> 
    #include <cassert> 
    class EnumCouleur 
    { 
    public : 

     enum tEnumCouleur{BLACK,BLUE,RED,GREEN,YELLOW,CYAN}; 
    std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>(BLACK, "BLACK")(BLUE, "BLUE")(GREEN, "GREEN"); 

    //Getting an error with the "=" saying it's an unautorized initialisation 
//also getting an error at the end of std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>, asking for ";" 
     // static car ce get ne sappele pas sur un objet EnumCouleur (il sera toujours le même) cout<<EnumCouleurs::c_Str(v) 
     static const char * c_Str(tEnumCouleur l) { 
      return strEnumCouleur[l];} 
     std::map<std::string, tEnumCouleur> xmap; 
    private : 
     static char * strEnumCouleur[]; 
     //EnumCouleur(); 

    }; 

和一个.cpp,让我枚举转换为字符串:

#include "EnumCouleur.h" 
#include <string> 

char * EnumCouleur::strEnumCouleur[] = { 
    "BLACK","BLUE","RED","GREEN","YELLOW","CYAN" 
}; 

我已经试过这两个THI我在话题发现NGS我LINKD:

std::map<std::string, tEnumCouleur> xmap = boost::map_list_of("A", A)("B", B)("C",C); 

struct responseHeaderMap : public std::map<std::string, tEnumCouleur> 
{ 
    responseHeaderMap() 
    { 
     this->operator[]("BLACK") = BLACK; 
     this->operator[]("BLUE") = BLUE; 
     this->operator[]("RED") = RED; 
     this->operator[]("GREEN") = GREEN; 
     this->operator[]("YELLOW") = YELLOW; 
     this->operator[]("CYAN") = CYAN; 
    }; 
    ~responseHeaderMap(){} 
}; 

我真的不知道如何使用它..让说我的节目得到了从textdocument的字符串。我确定这个字符串是正确的。我想使作为tEnumCouleur,在方式,以适应构造器:

Segment(const Point p1, const Point p2, EnumCouleur::tEnumCouleur v);

我如何做到这一点吗?

+0

可能重复://计算器。 com/questions/7163069/c-string-to-enum) – Aleksandar 2014-11-20 20:27:11

+0

你读过船长吗? – Niko 2014-11-20 20:30:27

+1

@尼科它是这个问题的重复。你不明白答案的事实并没有改变这一点。 – Daniel 2014-11-20 20:31:55

回答

1

你实际上需要做的是翻转你的std::map左右,所以它将字符串映射到enum而不是enum字符串。然后,你可以做xmap[string]并得到你的enum

所以,你可以做

std::map<std::string, tEnumCouleur> xmap = boost::assign::map_list_of<std::string, tEnumCouleur>(A, "A")(B, "B")(C, "C"); 

,然后你可以简单地做xmap["BLACK"],你会得到枚举值BLACK [C++字符串枚举(HTTP的

+0

另外,在您发布基于我的问题的问题的确切时刻,我碰巧打开了SO,这完全是巧合。 – Daniel 2014-11-20 20:20:04

+0

我不明白你的意思是“翻转”我的地图对不起..所以它是std :: map = ...但我需要把它放在哪里? – Niko 2014-11-20 20:24:27

+0

“,你会得到字符串”黑“”,你的意思是枚举权?因为我想要的是枚举! – Niko 2014-11-20 20:25:46