C++结构体在字段事先未知时

huangapple go评论58阅读模式
英文:

C++ structs when fields not known beforehand

问题

我有一个C++程序,根据关键字从二进制/ASCII文件中读取数据,并将数据分配给每个关键字作为向量。
我首选的数据结构来存储数据并在以后使用它的是结构体。问题在于每个文件可能有关键字,也可能没有,并且初始化一个包含所有可能字段的综合结构体也很麻烦。我之前的研究表明,没有办法初始化一个没有字段的结构体,然后再添加字段。这是这种情况吗?是否有任何解决方案或您推荐的替代数据结构?
提前致谢。
示例代码:

std::struct s {};
std::map<std::string, std::vector<std::string>> records;
//读取ASCII文件后的结果:records映射将具有
//字符串键和向量值。
//我需要将单独的键和值分配给结构体s

我尝试将关键字字符串分配为字段名称,但没有成功。

以下是一部分文件内容,供那些要求的人查看:

> dimens 60 220 85 /
> 
> tops 13200*3657 /
> 
> dx 1122000*6.096
> 
> dy 1122000*3.048
> 
> dz 1122000*0.6086
英文:

I have a C++ program that reads data from a binary/ascii file according to keywords and assign the data to each keyword as vectors.
My preferred data structure to store the data and use it afterwards is structs. The issue is that each file may or may not have some of the keywords and having a comprehensive struct initialized with all possible fields is troublesome as well. My previous research lead to understanding that there is no way to initialize a struct with no fields and then adding fields later. Is this the case? and are there any solutions or alternative data structures that you would recommend?
Thank you in advance.
Example Code:

   std::struct s {};
   std::map&lt;std::string, std::vector&lt;std::string&gt;&gt; records;
   //result after reading an asci file: the records map will have
   //keys as strings and values as vectors.
   //What I need is to assign the individual keys and values to 
   //struct s

I tried assigning keyword string as field names but it did not work.

Here is a portion of the file contents for those who requested:

> dimens 60 220 85 /
>
> tops 132003657 /
>
> dx 1122000
6.096
>
> dy 11220003.048
>
> dz 1122000
0.6086

答案1

得分: 3

在C和C++中,根据用户输入无法添加结构字段。实际上,所有字段(包括名称和类型)必须在编译时已知。

在C++中,基于用户输入存储键值对的典型数据结构是std::map(还有其他选项,如std::unordered_map)。如果字段类型也不固定,一种解决方法是为值定义自己的类,这个类可以容纳所有可能类型的值。

英文:

In C and C++ it's not possible to add struct fields based on user input. In fact, all fields (with name and type) must be known at compile time.

A typical data structure to store key--value pairs in C++ based on user input is std::map (there are others such as std::unordered_map). If the field types also vary, one way to solve it is defining your own class for the value, a class which can hold a value of all possible types.

huangapple
  • 本文由 发表于 2023年6月22日 03:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定