2017-10-28 98 views
-1

是這樣的可能,沒有運氣的任何地方找到它:C++比較變量,變量名

int numberA = 10; 
int numberB = 20; 
int numberC = 30; 



if (some string == B){ 
    int result = 5 + numberB; 
} 

編輯

+3

這個概念被稱爲「數組」。 – Jodocus

+4

使用數組.... – StoryTeller

+0

請不要在人們已經回答後大量改變問題的性質。 – Steve

回答

0

如果你不希望使用std::vectorstd::array或數組,你可以使用std::map文本名稱與變量關聯:

int numberA = 1; 
int numberB = 2; 
int numberC = 3; 
std::map<std::string, int *> variable_names; 
variable_names["numberA"] = &numberA; 
variable_names["numberB"] = &numberB; 
variable_names["numberC"] = &numberC; 
//... 
int * p_variable = variable_names[some_string]; 
*p_variable = 8; 

通常優選使用std::vectorstd::array並且可能使用std::list作爲容器變量或值。

2

不是直接的,但你可以這樣做:

std::vector <int> number (3); 

number[0] = 10; 
number[1] = 20; 
number[2] = 30; 

for (n=0; n<3; n++){ 
int result = 5 + number[n]; //so for n=1, it will be 5 + number1 = 5 + 10... 
} 

請注意,有更簡單的方法來初始化矢量,但爲了清晰起見,保持結構與問題相同。我還必須稍微更改for循環,因爲vector從0開始。

0

您必須初始化數組才能使其工作。

初始化一個整數數組,你可以這樣做:

int num[]= {10, 20, 30}; 
for(int n= 0; n< 3 ; n++) { 
     int result = 5+ num[n]; 
} 

陣列有一個從0開始。 索引你的數組有三個元素,但索引0-2 走這應該工作

+0

'num'將在n = 3時溢出。 – Seeker

+0

我修正了這個錯誤 – Nora

1

不可以。就C++而言,變量名在運行時不存在。