gpt4 book ai didi

c++ - 结构成员访问 - 命令行

转载 作者:行者123 更新时间:2023-11-28 01:09:50 25 4
gpt4 key购买 nike


这可能是一个简单的问题,但我无法弄清楚。我有这样的结构。


struct emp
{
int empid;
string fname;
}
emp e[10];

我在 e[10] 中有一些数据。


e[0].empid = 1 , e[0].fname = "tanenbaum"
e[1].empid = 2 , e[1].fname = "knuth"
.....

现在,如果我给出这样的输入命令行:


emp , empid

现在我需要访问结构 emp.empid。如果我有 10 个其他结构,我需要访问它们,当输入给出类似结构标签和结构成员时。在这里我无法弄清楚如何将字符串变量(emp、empid)附加到结构成员(emp.empid)。提前致谢。编辑这是我的程序。


int main(int argc, char *argv[])
{
char *tag_name = argv[1]; //emp (structure tag name)
char *member_name = argv[2]; // empid (structure member name)
int data = argv[3]; //value: 2
/* I need some mechanism that will convert those tag_name.member_name
to original structure memmber access<br/>
tag_name(emp).member_name(empid) == value (2)
Is there any way to map like this
*/
return ;
}

最佳答案

编辑:使用指向成员运算符的指针,您可以实现您想要的。您需要使用 std::map 创建小型数据库。

下面是工作程序。

#include <iostream>
#include <string>
#include <map>
using namespace std;
struct emp
{
int empid;
int salary;
};

int main(int argc, char *argv[])
{
//member map stores member varialbe names and corresponding offsets.
map<string, int emp::*> memberMap; //It can store offsets of only integer members.

//tagMap stores tag names and object pointer
map<string, emp *> tagMap;

//Allocate for 10 records
emp *e = new emp[10];
//Store sample data in those records.
for(int i = 0; i < 10; i++)
{
e[i].empid = (i+1) * 10;
e[i].salary = (i+1) * 1000;
}

//Populate tag map with tag names and corresponding object pointers
//As of now, we have only emp structure.
//You can add more structures similar to below.
tagMap.insert(pair<string, emp *>("emp", e));

//Get the offsets of member variables of emp structure.
int emp::*offset_empid = &emp::empid;
int emp::*offset_salary = &emp::salary;

//Populate member map with member names and corresponding offsets
memberMap.insert(pair<string, int emp::*>("empid", offset_empid));
memberMap.insert(pair<string, int emp::*>("salary", offset_salary));

//Am passing tag name in argv[1], member name in argv[2] and record id in argv[3] from
//command line
string tagName = argv[1]; //tag name
string memberName = argv[2]; //member name
int recordId = atoi(argv[3]);//record id

//Access member specified like below.
cout<<"Employee details requested are : "<<endl;
cout<<memberName<<"\t"<<(tagMap[tagName]+recordId)->*memberMap[memberName];

//Free the allocated memory.
delete []e;
}

输入:

emp salary 2

输出:

Employee details requested are : salary 3000

我希望你能通过我写的评论理解这个程序。

输入:我提供 tagName、fieldName 和 recordId。

输出:我从请求的记录 ID 中获取请求的字段值。

关于c++ - 结构成员访问 - 命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3993749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com