如何使用一个变量,在C++中另一个变量

问题描述:

的名字我使用的是结构如下图所示:如何使用一个变量,在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

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

谢谢,它解决了我的问题。 –