我正在使用如下结构:
struct Employee{
string id;
string name;
string f_name;
string password;
};
我想要一个 for 循环,每次我递增我都想从我的结构中创建一个对象,如下所示:
for(int i= 0; i<5; i++){
struct Employee Emp(i) = {"12345", "Naser", "Sadeghi", "12345"};
}
我想要的只是通过每次将 i 的值添加到它们名称的末尾来拥有不同名称的对象,例如 Emp1。
最佳答案
C++ 没有您要求的确切功能。为了将事物放在一起,您需要使用数组或其他容器。然后,为了访问,您必须使用索引器。
以下是您问题的有效解决方案(也是 here ):
#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;
}
关于c++ - 如何在 C++ 中使用另一个变量名中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273028/