C ++通过变量的连接名称获取变量值

时间:2015-12-11 10:35:51

标签: c++ variables reference concatenation

我不知道这是否可行,但我会试着解释一下:

我有以下变量:

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

}

这对我的问题是一个很好的推理还是存在这种方法?

1 个答案:

答案 0 :(得分:5)

只需使用std::map<std::string, std::string>

这样你可以这样做:

var geoCoder: CLGeocoder = CLGeocoder()

如果密钥(在本例中为字符串)不存在,则运算符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; 将添加到地图中,如果密钥存在,则会更改该值。