2016-05-17 203 views
1

的名字我使用的是結構如下圖所示:如何使用一個變量,在C++中另一個變量

struct Employee{ 
string id; 
string name; 
string f_name; 
string password; 
}; 

我想有一個循環,每一次,我增加我我想要的對象從我的結構是這樣的:

for(int i= 0; i<5; i++){ 
struct Employee Emp(i) = {"12345", "Naser", "Sadeghi", "12345"}; 
} 

所有我想要的是有哪些加入我的價值,他們的名字一樣EMP1每次結束都是不同的名字對象。

+0

你不能做到這一點:

下面爲你的問題(也here)工作方案。如果你告訴你正在試圖完成的事情,我們可能會提供幫助。 – TartanLlama

+1

查找'array'和'std :: vector'。 –

+0

你不能在C++中做到這一點;某些解釋型語言提供此功能。爲什麼在'for'循環體中需要唯一命名的變量?每次迭代開始時都會創建一個新的變量,這不像您會遇到名稱衝突。 – szczurcio

回答

4

C++沒有確切的功能,你要求。爲了保存事情,你需要使用數組或其他容器。然後,爲了訪問你必須使用索引器。

#include <vector> 
#include <iostream> 
#include <string> 

struct Employee { 
    std::string id; 
    std::string name; 
    std::string f_name; 
    std::string password; 
}; 

int main() { 

    std::vector<Employee> employees; // vector for keeping elements together 

    for (int i = 0; i<5; i++) { 
     // push_back adds new element in the end 
     employees.push_back(Employee{ "12345", "Naser", "Sadeghi", "12345" }); 
    } 
    std::cout << employees.size() << std::endl; // 5 returns how many elements do you have. 
    std::cout << employees[0].name; // you access name field of first element (counting starts from 0) 

    return 0; 
} 
+1

謝謝,它解決了我的問題。 –

相關問題