开发者

Equivalent of Enum for Strings

I studied enums which expects only integer inputs and returns corresponding value to it.I want to achieve same thing but I only开发者_JAVA百科 have strings as a input. I want to make following work -

enum Types {
"Absolute", //"abs"
"PURE", //"PRE"
"MIXED" //"MXD"
}

and probable statment could be -

string sTpes = Types("abs"); //this should return "Absolute"

or

string sTpes = Types("MXD"); //this should return "MIXED"

If not using enums, please suggest me possible ways to achieve this.

Thanks.


There are no "string-enums", but to map from one value to another, you can use std::map, which is a standard template shipped with C++ platforms:

#include <map>
#include <string>

int main() {
    using std::map;  using std::string;

    map<string, string> ss;
    ss["abs"] = "Absolute";

    const string foo = ss["abs"];
    std::cout << ss["abs"] << ", or " << foo << std::endl;
}

In C++0x, if you want "safe" access that throws an exception if the key-type wasn't found, use map::at (actually, afair, the lack of map::at was just an oversight in the current standard):

    std::cout << ss.at("weird keY");

or check if it exists:

    if (ss.find("weird keY")==ss.end())
        std::cout << "key not found\n";


if you are talking about c++/cli you could use this Hashtable^ openWith = gcnew Hashtable();

    // Add some elements to the hash table. There are no
    // duplicate keys, but some of the values are duplicates.
    openWith->Add("txt", "notepad.exe");
    openWith->Add("bmp", "paint.exe");
    openWith->Add("dib", "paint.exe");
    openWith->Add("rtf", "wordpad.exe");

from http://msdn.microsoft.com/fr-fr/library/system.collections.hashtable.aspx#Y4406 else use map from stdlib.

I think you can also use CMAP from MFC, there is a good article about it here : http://www.codeproject.com/KB/architecture/cmap_howto.aspx


An enum has an integral value. Personally I simply suggest two conversion functions:

  • enum -> string
  • string -> enum

The first can be implemented with a simple array, the second require a binary search in a sorted list.


you could use a string array (of size 2) from string.h i think (either that or just string; one is for C and other is for cpp). first string is "abs" second is "absolute".

for example:

#include <string>

...

string abs[2]; //or a better name that's more relevant to you

abs[0] = "abs";
abs[1] = "absolute";

...

//pass it into the function
cout << abs[1] << endl;

...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜