maping two values via enum

Hi

I've two values
eg

enum
{
zero_t = 0,
one_t,
two_t,
}
from one funciton I'll get this enum value.

but acutal string value of zero_t = "ZERO"
i need to convert that zero_t to "ZERO".

On otherway I'llget a string "ZERO" i need to convert to zero_t.

How to do this??

You can't stick a string in an enum, but here is what you can do:

 ``123456789`` ``````enum eNumber { zero_t = 0, one_t, two_t, eNumbersize, }; string NumStrings[eNumbersize] = { "ZERO", "ONE", "TWO" };``````

Then to convert your enum into a string:
`cout << NumStrings[zero_t];`

this will give zero_t to ZERO.

But I need
"Zero" to zero_t also.

both viseversa I need.

basically encoding and decoding.
If you don't want boost, this could work:
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` ``````#include #include #include #include enum eNumber { zero_t , one_t, two_t, }; template class bimap { typedef std::pair _PAIR; typedef std::vector<_PAIR> _SET; _SET set; public: void push_back(const Left l, const Right r) { set.push_back( _PAIR (l,r) ); } Left getLeft(Right r) { for ( _SET::iterator it = set.begin(); it != set.end(); ++it) if (it->second == r) return it->first; return set.begin()->first; } Right getRight(Left l) { for ( _SET::iterator it = set.begin(); it != set.end(); ++it) if (it->first == l) return it->second; return set.begin()->second; } }; int main() { bimap NumSet; NumSet.push_back(zero_t,"ZERO"); NumSet.push_back(one_t,"ONE"); NumSet.push_back(two_t,"TWO"); std::cout << NumSet.getRight(zero_t) << std::endl; std::cout << NumSet.getLeft("ONE") << std::endl; return 0; }`````` ```ZERO 1```
Last edited on
And here it is a little more specified (less generalized) for readability if you don't plan to port it to other stuff:
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` ``````#include #include #include #include enum eNumber { zero_t , one_t, two_t, inval_t, }; class bimap { typedef std::pair _PAIR; typedef std::vector<_PAIR> _SET; _SET set; public: void push_back(const eNumber n, const std::string s) { set.push_back( _PAIR (n,s) ); } eNumber getNum(const std::string s) { for ( _SET::iterator it = set.begin(); it != set.end(); ++it) if (it->second == s) return it->first; return inval_t; } std::string getStr(const eNumber n) { for ( _SET::iterator it = set.begin(); it != set.end(); ++it) if (it->first == n) return it->second; return ""; } }; int main() { bimap NumSet; NumSet.push_back(zero_t,"ZERO"); NumSet.push_back(one_t,"ONE"); NumSet.push_back(two_t,"TWO"); std::cout << NumSet.getStr(zero_t) << std::endl; std::cout << NumSet.getNum("ONE") << std::endl; return 0; }`````` ```ZERO 1```
Last edited on
Topic archived. No new replies allowed.