0

たとえば、どこかからデータを取得し、それを文字列変数に入れ、その内部のデータを別の文字列名として使用したいとします。

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++ は動的変数言語ではなく、最も近いのはマップ (文字列、文字列) を使用することです。

4

4 に答える 4

2

あなたが考えているような明確なものは何もありませんが、おそらくあなたは興味がある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;
}
于 2012-06-25T04:15:10.110 に答える
0

C++ では、変数名はコンパイル時にのみ存在します。最も近いのは、文字列キーを持つマップを使用することです。

于 2012-06-25T04:13:19.723 に答える
0

何を求めているのかわかりませんが、「動的な」変数名が必要な場合は、コードで直接行うことはできません。マップ型のデータ構造を使用する必要があります。または、標準ライブラリを使用できるstd::hash_setかどうかを確認してください。std::map

于 2012-06-25T04:14:57.710 に答える
0

変数を動的に作成できる言語がありますC++ はその 1 つではありません ;)

于 2012-06-25T04:17:22.277 に答える