动态地为结构变量赋值 [英] Dynamically assigning value to structure variable
问题描述
我试图动态地将值从文件中的结构中的变量,但不能弄清楚如何做。我有一个结构:
struct abc {
int age = 0;
string name =whatever;
} * ABC;
我还有一个函数循环通过一个文件,可以读取这些值,一个包含变量名称及其需要更新的值的行。例如,我可能会得到两个变量,如:
KEY =age
VAL = 21
之后,会出现以下文件的第一行:
age | 21
name | bill
如何将VAL值赋给ABC结构变量KEY?
谢谢!
UPDATE:
所以我想做类似的工作:
ABC.KEY = VAL
意义
ABC.age = 21
如果你想将键匹配到结构的成员
例如,您可以考虑这样:
std :: unordered_map< std :: string,std :: function< void(std :: string,abc&)>映射;
mapping [age] = [](std :: string str,abc& a){a.age = std :: stoi(str); };
mapping [name] = [](std :: string str,abc& a){a.name = str; }
现在您可以使用
这样的地图 abc输出;
auto key = ...
auto value = ...;
if(mapping.find(key)== mapping.end())
throw ...;
mapping [key](value,output);
I am trying to dynamically assign values from a file to variables in a structure, but can't figure out how to do it. I have a structure:
struct abc {
int age = 0;
string name = "whatever";
} *ABC;
I also have a function that loops through a file that can read these values so I would end up with a line that contains the variable name and its value that would need to be updated. So, for example, I might end up with two variables like:
KEY="age"
VAL="21"
after it processes the first line of the following file:
age|21
name|bill
How would I assign the VAL value to the ABC struct variable KEY?
Thanks!
UPDATE:
So I'm looking to do something like:
ABC.KEY = VAL
meaning
ABC.age = 21
What you're looking for is known as reflection, and C++ does not offer this capability.
If you want to match keys to members of the struct, you will have to build a structure and functions to do so yourself.
For example, you may consider this:
std::unordered_map<std::string, std::function<void(std::string, abc&)>> mapping;
mapping["age"] = [](std::string str, abc& a) { a.age = std::stoi(str); };
mapping["name"] = [](std::string str, abc& a) { a.name = str; }
Now you can use the map like
abc output;
auto key = ...;
auto value = ...;
if (mapping.find(key) == mapping.end())
throw ...;
mapping[key](value, output);
这篇关于动态地为结构变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!