c++ , how to store string,int and float values into an array and retrieving back the stored values
Solution 1
For basic types, this would be easy: they can be mixed into a union
, http://www.cplusplus.com/doc/tutorial/other_data_types/ (->Unions).
For complex types, like string
, it gets a little more difficult.
You might want to look at boost::variant
, http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html or boost::any
http://www.boost.org/doc/libs/1_51_0/doc/html/any.html
Solution 2
if these values are related, then create a struct and store that instead of individual values. ex:
struct person {
string name;
int age;
};
person pArray[];
Related videos on Youtube
Heng Aik Hwee
Updated on September 16, 2022Comments
-
Heng Aik Hwee over 1 year
Is an array possible to store
int
,string
andfloat
all at the same time? I have been seeing some array syntax but all starts withint array[]
orstring array[]
, is there a way which a array can store all kind of primitive and string values?Im not very familiar with C++ but in java there is a iterator which can help you roll those stored values out and allow you to display what is stored in there. Does C++ also have this feature?
-
leo over 11 yearsI know this isn't really helpful, but why do you need to do this? Having an array with several types on it can be quite confusing. Could you try modelling your solution differently?
-
Tom Kerr over 11 yearsFor what it's worth, I doubt that a class would give you an assignment that requires boxing types like this. You may be misunderstanding a requirement. Perhaps an opportunity for polymorphism?
-
-
Rudolf Mühlbauer over 11 yearsgreat answer, if you don't care about memory footprint. you could also add a type-identifier
enum { IS_FLOAT, IS_STRING, ... }
to identify the type at runtime. -
Tom Kerr over 11 yearsHow would they know which value to use?
boost::optional
might help? -
Mooing Duck over 11 years@RudolfMühlbauer: I don't think he's recommending a union-like thing, he's actually recommending a rethinking of what it means to put multiple objects in an array (as an object)
-
Rudolf Mühlbauer over 11 years@MooingDuck yes, i know. still you might be interested to get the actual (inner) type at runtime. i was just suggesting, what seems as 'next steps' to me.