在上一个问题中,我把那里搞得一团糟。所以我想尝试一下。
struct emp
{
int salary;
string empid;
};
struct payroll
{
int empid;
int deductions;
};
emp a1,a2, a3;
a1.salary = 9000;
a1.empid = 1;
a2.salary = 1000;
a2.empid = 2;
a3.salary = 9000;
a3.empid = 3;
payroll p1,p1,p3;
p1.empid = 1;
p1.deductions = 10;
p12.empid = 2;
p2.deductions = 20;
p3.empid = 3;
p3.deductions = 30;
<p>now, from the command prompt i have given like this </p>
empid = 1;
然后我需要 a1 和 p1 的答案。
在这里,我需要检查结构是否具有成员名称:empid - 如果为真 - 然后检查 empid = 1。
如何以通用方式执行此操作。我的意思是如果我有 30 个这样的结构怎么办。给我任何想法,如果这不可能,那么如何使用任何其他数据结构来完成。
最佳答案
没有可移植的方法来动态检查结构的成员变量名。如果您不想检查成员变量名称,请使用 std::vector
来存储结构实例。使用 std::find_if
搜索满足谓词的特定实例。参见 this link find_if
的用法示例。如果您真的想检查 struct
中是否存在名为 empid
的字段,请改用 std::map
:
typedef std::map<std::string, int> emp;
typedef std::map<std::string, int> payroll;
typedef std::vector<emp> emp_list;
typedef std::vector<payroll> payroll_list;
emp_list emps;
emp a1;
a1["empid"] = 1;
a1["salary"] = 9000;
emps.push_back(a1);
// ...
payroll_list pays;
payroll p1;
p1["empid"] = 1;
p1["deductions"] = 10;
pays.push_back(p1);
// ...
// use an iterator over emps and pays to check for specific items
emp_list::const_iterator eit = emps.begin ();
emp_list::const_iterator eend = emps.end ();
while (eit != eend)
{
emp e = *eit;
int eid = e["empid"];
if (eid == empid)
{
std::cout << e["salary"] << '\n';
}
eit++;
}
// ...
关于c++ - 结构成员名称 - 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986275/