【问题标题】:Equivalent of Enum for Strings字符串的枚举等价物
【发布时间】:2011-08-10 11:21:56
【问题描述】:

我研究了只需要整数输入并返回相应值的枚举。我想实现同样的目标,但我只有字符串作为输入。我想做以下工作-

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

并且可能的陈述可能是 -

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

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

如果不使用枚举,请建议我实现此目的的可能方法。

谢谢。

【问题讨论】:

  • 您使用的是 C 还是 C++?对我来说它看起来像 C++。
  • @David: 既然你这么说,就更让人想起C#了:string是直接可用的,缺少';'在枚举后面。

标签: c++ c string enums


【解决方案1】:

没有“字符串枚举”,但要从一个值映射到另一个值,您可以使用 std::map,这是 C++ 平台附带的标准模板:

#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;
}

在 C++0x 中,如果您希望“安全”访问在未找到密钥类型时引发异常,请使用 map::at(实际上,缺少 map::at 只是在现行标准):

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

或检查它是否存在:

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

【讨论】:

    【解决方案2】:

    如果你在谈论 c++/cli 你可以使用这个 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");
    

    来自http://msdn.microsoft.com/fr-fr/library/system.collections.hashtable.aspx#Y4406 否则使用标准库中的地图。

    我认为你也可以使用 MFC 的 CMAP,这里有一篇很好的文章:http://www.codeproject.com/KB/architecture/cmap_howto.aspx

    【讨论】:

    • 投反对票者:详细说明或停止成为一个有疙瘩的巨魔。 +1 补偿。
    【解决方案3】:

    enum 具有整数值。我个人只是建议两个转换函数:

    • enum -&gt; string
    • string -&gt; enum

    第一个可以用一个简单的数组来实现,第二个需要在排序列表中进行二分查找。

    【讨论】:

      【解决方案4】:

      我认为你可以使用 string.h 中的字符串数组(大小为 2)(要么是字符串,要么只是字符串;一个用于 C,另一个用于 cpp)。第一个字符串是“abs”,第二个是“absolute”。

      例如:

      #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;
      
      ...
      

      【讨论】:

      • 我提到其中有 2 个:string.h 和 string。我不记得哪个是哪个
      • 但是std::string foo[2] 将如何帮助启用语法Enum("Value")?我想你基本上只是写下了你对这些问题的最初想法。
      • 它将替换枚举。如果您将 2 个字符串存储在其中,那么当它传入时,只需将其返回或打印您想要的任何值。 cout
      • 你可以制作字符串数组
      • 但是 OP 想要像 Enum("Value") 这样的语法,OP 不想硬编码数组索引。
      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2010-12-25
      • 1970-01-01
      相关资源
      最近更新 更多