【问题标题】:C++ Get variable value by concatenated name of the variableC ++通过变量的连接名称获取变量值
【发布时间】:2015-12-11 10:35:50
【问题描述】:

我不知道这是否可能,但我会尽力解释:

我有以下变量:

const char * VAR1 = "var1";
const char * VAR2 = "var2";

const char * VAR1_A = "etc1";
const char * VAR2_A = "etc2";

然后我声明一个std:vector 并将变量放入:

vector <const char *> v1;
v1.push_back(VAR1);
v1.push_back(VAR2);

然后我以这种方式遍历向量以找到匹配项:

const char * param = "var1"; //Example parameter

for(int x=0; x<v1.size(); x++){

   //Found a match in the vector
   if(param == v1[x]){

      //HERE is the point. I need to get the value of variable "[v1[x](NAME)]_A"
      //Something like:
      const char * varname = getVarName(v1[x]) + "_A"; //This would contain VAR1_A
      const char * varvalue = getVarValueByVarName(varname); //This would contain "etc1";
      break;
   }

}

这是解决我的问题的一个很好的理由还是有解决这个问题的现有方法?

【问题讨论】:

    标签: c++ variables reference concatenation


    【解决方案1】:

    只需使用std::map&lt;std::string, std::string&gt;

    这样你就可以做这样的事情:

    map<string, string> myMap;
    myMap["var1"] = "var1_value";
    myMap["var2"] = "var2_value"; 
    //say now you get input into a variable named 'str' for what variable the user wants to print
    cout << myMap[str] << endl;
    

    如果键(在本例中为字符串)不存在,运算符[] 将添加到映射中,如果存在则更改值。

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 2019-05-13
      • 2016-12-18
      • 2014-06-15
      • 2015-08-16
      • 1970-01-01
      • 2014-02-08
      • 2023-03-16
      • 2018-10-20
      相关资源
      最近更新 更多