+ 1

Array of different types

C++ I need an array of pointers to different types of data.( like in python ). I suppose, that it can be done with templates. Please, depict it shortly in words ( i want to code it by myself)

7th Apr 2020, 9:38 PM
Denis
Denis - avatar
13 Respuestas
+ 5
It can be a cool exercise and all but here's why mixed-type arrays are not useful: - Arrays can be of any length. - The only way to run through a whole array is using a loop. - In the loop body, we are running the same block of code for each element. - To make that work, every element needs to be of the same type. That's not to say that we can't have multiple types in an array. But variable types + variable length is not helpful / nonsensical. We can fix the set of types, like so: union many_types { int a; float b; char c; } std::vector<many_types> arr; Or we can fix the length, like so: std::tuple<int, float, char> tup; It's an either/or situation. You can have arbitrary types with fixed length, or arbitrary length with fixed types, but not both.
8th Apr 2020, 12:29 AM
Schindlabua
Schindlabua - avatar
+ 3
Why do you (think you) need it? Can you describe your situation? Because there might be a more natural way.
7th Apr 2020, 10:17 PM
HonFu
HonFu - avatar
+ 2
i read , that in python it is realised via pointers, thus i think , that its the most simple way Originally task was to make an array of any type via templates, but i decided to improve it a bit
7th Apr 2020, 10:26 PM
Denis
Denis - avatar
+ 2
Did they actually mean, that your array should work for mixed types, or that it should work for *one* version of the template, like vector<int> for example?
7th Apr 2020, 10:36 PM
HonFu
HonFu - avatar
+ 2
yes, only for one version. But I decided to know how to make for multiple types
7th Apr 2020, 10:41 PM
Denis
Denis - avatar
+ 2
Just to make sure: You want to have an int at spot 0, a char at spot 1, a double at spot 2...
7th Apr 2020, 11:00 PM
HonFu
HonFu - avatar
+ 2
yes
7th Apr 2020, 11:08 PM
Denis
Denis - avatar
+ 2
oh, thanks a lot
7th Apr 2020, 11:13 PM
Denis
Denis - avatar
+ 1
Hm. I think there was some homepage where the algo Python uses is described. Python's written in C after all. Now where did I see that...
7th Apr 2020, 11:10 PM
HonFu
HonFu - avatar
+ 1
It might be 'slightly' harder than the original task though! 🤣 Good luck!
7th Apr 2020, 11:15 PM
HonFu
HonFu - avatar
+ 1
Zandi - kurdish Programmer, can you explain the relationship of your answer to the question?
7th Apr 2020, 11:43 PM
HonFu
HonFu - avatar