Reputation: 6161
Let's say I'm reading a table from a file but the set of columns isn't defined in principle (they are defined in the first line of the file). I'm thinking to make a list of objects read from the file. The first line has the titles and in the following lines each line has the object values. Each object might be a struct but in this case I'll have to define the structure fields (the column names) in execution time.
How to approach this issue?
I'm using Qt. Clever approaches then mine (described above) are welcome.
Exemple, table names:
FirstName LastName
sdasdc bdfgdg
drtggw nhnfgh
wrew rtyhrt
Upvotes: 0
Views: 104
Reputation: 4689
You can put your data in the QMap<QString, QVariant>
(QVariant
acts like a union for the most common Qt data types). So, it will be easy for you to name each field of your structures, and to get an access to the data by name (not by index).
Also you can just use QList<QVariant>
. It sounds a little simpler, but in this case you will use indices for getting values from this "structure" (so the code will be not so clear), so I'd recommend you to use QMap
.
Update:
So, QMap<QString, QVariant>
or QList<QVariant>
is an item in the list. Since you need to have a list of such items, you will use QList<QMap<QString, QVariant>>
or QList<QList<QVariant>>
.
Let's compare these options:
If you have very small list (like in your example - only three items), it will be ok to use QList<QMap<QString, QVariant>>
. In this case there will be three copyes of each title of each column. But it will be easy to get any information about any item.
If you need to process very big lists, it is much more effective to use QList<QList<QVariant>>
. In this case you'll put titles of the columns in the first element of the list, and the rows with data into next items of this list. It is more effective (you spend less memory), but a little more complex to process.
Upvotes: 1