c++ - 如何在 C++ 中使用另一个变量名中的变量

标签 c++

我正在使用如下结构:

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/

相关文章:

c++ - 保存和加载 C++ 程序

c++ - 在 Windows 中更改 boost 线程优先级

c++ - Qt 在 Linux 上不显示 PNG 图像

c++ - 错误CC2061 : syntax error: identifier 'GLUquadric'

c++ - 如何在 C++ 中创建动态结构数组?

c++ - 编译器生成的复制构造函数/赋值是否使用 const/volatile 呈现它的参数

c++ - 字符串指针上的 strcpy 给出错误

c++ - 未解析的外部符号 cvFindChessboardCorners()

c++ - 当 C++ 中需要自动删除时,这种静态用法是否正确?

c++ - Direct3D9 无法让垂直 fov 相机工作