【问题标题】:Declare variables names using string value data in cpp/c++在 cpp/c++ 中使用字符串值数据声明变量名称
【发布时间】:2012-06-25 04:09:49
【问题描述】:

例如,假设您从某处提取数据并将其放入字符串变量中,然后您想使用其中的数据作为另一个字符串名称:

int main(void){

   string strVar ="StringData"; //this is a string variable with text inside 

   cout<<strVar<<endl;    //displaying the variables contents


   string strVar.c_str() = "stuff in string variable 'StringData'"; //this uses what was inside of strVar to be the name of the new string variable

   cout<<StringData<<endl; //prints the contents of the variable StringData (who got its name from the data inside of strVar
}

//OUTPUT:
StringData
stuff in string variable 'StringData'

我知道你绝对不能以这种方式做到这一点,在这个例子中,你必须在使用变量 StringData 之前事先知道 strVar 中的内容,但理论上我们可以这样做吗?

编辑:

谢谢大家,所以我从你们那里得到的基本上是不可能的,C++ 不是动态变量语言,我能得到的最接近它的是 地图(字符串,字符串)

【问题讨论】:

  • 大概map&lt;string, string&gt;是你想要的?
  • 简短的回答:不,不可能。

标签: c++ c variables declaration


【解决方案1】:

没有什么像你想的那样,但也许你会对std::map 感兴趣?听起来您想要的是键值对。

std::Map 参考 -> http://www.cplusplus.com/reference/stl/map/

例子:

#include <map>
#include <string>
#include <iostream>
using namespace std;

int main(void)
{
    map<string, string> myMap;
    myMap.insert(pair<string, string>("StringData", "Stuff in StringData"));

    // Get our data
    cout << myMap["StringData"] << endl;

    return 0;
}

【讨论】:

    【解决方案2】:

    变量名仅在 C++ 的编译时存在。最接近的方法是使用带有字符串键的地图。

    【讨论】:

    • 那么,我必须认真重新考虑我对这个程序的处理方式,感谢@Antimony 的帮助
    【解决方案3】:

    我不确定你在问什么,但如果你想拥有“动态”变量名,那么你不能直接在代码中这样做。您将不得不使用一些地图类型的数据结构。看std::hash_set或std::map是否可以使用标准库。

    【讨论】:

      【解决方案4】:

      有种语言可以让您动态创建变量。 C++ 不是其中之一;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-19
        • 1970-01-01
        • 2011-02-24
        相关资源
        最近更新 更多