简体   繁体   English

动态获取结构中成员的值

[英]get value of member in structure dynamically

Here there is a structure:这里有一个结构:

struct date
 {
  int day;
  int month;
  int year;
 }frmt;

A structure is initialized and members are assigned values.一个结构被初始化,成员被赋值。 Now, I want to get value of a member using dynamic variable.现在,我想使用动态变量获取成员的值。

Generally we use frmt.day to get value of that member.通常我们使用 frmt.day 来获取该成员的价值。 Now let std::string str1="day";现在让 std::string str1="day"; How can i get member value using str1?如何使用 str1 获取成员值? Can I use str1.c_str() ??我可以使用 str1.c_str() 吗??

You can use std::map<std::string, int> or std::unordered_map<std::string, int> for you simple struct in the example.您可以使用std::map<std::string, int>std::unordered_map<std::string, int>作为示例中的简单结构。 In this case you should in all places in your code replace frmt.day with frmt["day"] and etc. Thus you can call frmt[str1] .在这种情况下,您应该在代码中的所有位置将frmt.day替换为frmt["day"]等。因此您可以调用frmt[str1]

If a struct has members of various types, you could use std::variant instead of int (since C++17).如果结构具有各种类型的成员,则可以使用std::variant代替int (C++17 起)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM