【问题标题】:How do you use a string or char to identify a variable by name in C++? [duplicate]如何在 C++ 中使用字符串或字符来按名称识别变量? [复制]
【发布时间】:2016-12-11 20:41:32
【问题描述】:

我的意思是,如何使用可以迭代的字符来识别变量? 所以如果:

int cheese = 1337;
string identifier = "cheese";

如何使用这个字符串“标识符”来识别变量cheese并返回它的值?

【问题讨论】:

  • 这在 C++ 中是不可能的
  • C++ ulike Java 没有反射,因此程序一旦完全编译、链接和加载,它就会失去对符号名称的所有引用。唯一的就是地址。

标签: c++


【解决方案1】:

你没有。

相反,您以不同的方式布置数据,也许使用键值存储?

std::map<std::string, int> myData;
myData["cheese"] = 1337;

// ...

const std::string identifier = "cheese";
std::cout << myData[identifier] << '\n';   // 1337

【讨论】:

  • 我明白了。唔。我有什么办法在Java中做到这一点?除了使用哈希图,还是其他字典存储?
  • @JackRaiden:在...Java???
【解决方案2】:

您似乎在寻找map

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<string, int> vars;
    vars.insert(make_pair("cheese", 1337));
    vars.insert(make_pair("geese", 1338));
    if (vars.find("cheese") != vars.end())
        cout << vars.at("cheese");
    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2012-02-21
    • 2019-07-03
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多