+ 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)
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.
+ 3
Why do you (think you) need it?
Can you describe your situation?
Because there might be a more natural way.
+ 3
+ 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
+ 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?
+ 2
yes, only for one version. But I decided to know how to make for multiple types
+ 2
Just to make sure:
You want to have an int at spot 0, a char at spot 1, a double at spot 2...
+ 2
yes
+ 2
oh, thanks a lot
+ 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...
+ 1
It might be 'slightly' harder than the original task though! 🤣
Good luck!
+ 1
Zandi - kurdish Programmer, can you explain the relationship of your answer to the question?