如何为结构的数据元素赋值
How to assign values to the data elements of a structure
我有一个结构
struct MyStruct
{
int intValue1;
float floatValue2;
std::string stringValue3;
} Structure;
现在基于两个字符串的值输入,我想为结构的数据元素赋值:
std::string varName = "intValue1";
std::string varValue = "5";
因此,基于这两个字符串,"intValue1"应获得值 5
Structure.intValue1 = (int)varValue;
是否可以编写一个函数,该函数将根据输入字符串自动为结构赋值,例如:
void SetData( std::string varName , std::string varValue );
是的,这是可能的,使用字符串化运算符。下面是一个简约的例子:
#include <string>
#include <iostream>
#define NAME_OF( v ) #v
struct MyStruct
{
int intValue1;
float floatValue2;
std::string stringValue3;
} Structure;
int main()
{
MyStruct A;
std::string varName = "intValue1";
std::string varValue = "5";
auto var_name = NAME_OF(A.intValue1);
if (varName.compare(var_name) != 0) {
A.intValue1 = std::stoi(varValue);
}
std::cout << A.intValue1 << " " << varValue << std::endl;
}
希望这有帮助!
相关文章:
- 为什么复制而不是移动数据元素?
- 设计将引用元素移动到开头的数据结构.C++
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 如何为结构的数据元素赋值
- C++ Expat 仅打印元素的第一个字母和标签中的数据
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 从自定义数据类型向量中删除重复元素
- C++ - 按自定义数据类型向量的值删除元素
- Getter 函数,用于在 2d 数组是类的数据成员时检索 2d 数组元素
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 使用 dectlype 推断模板元素类型中的数据类型是否正确?
- 用于查找元素的数据结构
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
- 派生类中的数据元素
- 如何比较和存储 2 个向量的数据元素位置
- 如何在c++中处理大数据元素
- 链表,每个键包含多个数据元素
- 模板链表获取复杂数据类型的数据元素