2014-11-20 225 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