+ 1
how do I create an array that can contain both int and string values???????
how do I create an array that can contain both int and string values? Pls help me
7 ответов
+ 5
For example :
int arr = ["Hi", 78, true, 21];
cout << arr
+ 4
Hi Sofia,
To create a array which contains all value type, he can contains the strings, ints, functions, values...
+ 4
// Anna OK
+ 4
Use union in array
https://code.sololearn.com/clEcW9uXk6TM/?ref=app
+ 3
// Zohir Could you provide a link to a code sample in the playground where this actually works? 🤔
+ 2
Use std::tuple https://en.cppreference.com/w/cpp/utility/tuple
0
Sofia,
Why are you trying to do this? Maybe the community can help.
C++ is a statically typed language which means that data types are chosen by the programmer while working the code and strictly enforced by the compiler at compile time.
Arrays are data structures where all elements in the array are of the same data type.
Depending on your needs another data structure might be a better fit.
If it must be an array you might choose to make an array of strings and interpret the numbers as int later, assuming none of your strings are just numbers (e.g. [50, "50"]).
Another possible solution would be to use an array of void pointers (e.g. void * myArr ). You would then some int pointers (e.g. int * someInt) and string literals in the array (e.g. const char * someString). You wouldn't have an easy way of reading or changing the data, you would have to know the type of data a void pointer points to before accessing it.