+ 1
It's an integer array. You can only store int type in array "arr" there. Arrays in c/c++/java are homogenious (same) type data structure.
9th Feb 2022, 3:40 PM
Jayakrishna šŸ‡®šŸ‡³
+ 1
Instead of Union, better to use structure. and vector of vector may works. And ' variant '(as shown in above code by @lona), ' tuple ', classes may help in that case. But its some complex to understand now. (I think it's works only above c++11 only) edit: Manav Roy #include <iostream> #include <tuple> using namespace std; struct st { int i; string s; double d; }; int main() { cout<< "by using structure\n" : st a = { 30, "abc", 12.5}; cout << "int " << a.i << "\nstring: " << a.s <<"\ndouble : "<<a.d<<'\n'; std::cout << "\nusing tuple\n\n"; tuple<int, string, double> t{ 30,"Abc",12.5 }; cout<< get<0>(t)<<"\n"; cout<< get<1>(t)<<"\n"; cout<< get<2>(t); return 0; }
10th Feb 2022, 11:31 AM
Jayakrishna šŸ‡®šŸ‡³
0
Hi, you could try union or if using STL, then std::variant. #include <iostream> #include <variant> union myDataType { int i; char ch; }; int main() { myDataType arr[4] = { 11, 20, 30, 40}; arr[2].ch = 'h'; for (const myDataType& i : arr) { std::cout << "int form: " << i.i << " char form: " << i.ch << '\n'; } // STL c++17 std::cout << "using C++ 17\n\n"; std::variant<int, char> arr2[] = { 11, 20, 30, 40 }; arr2[2] = 'h'; for (const std::variant<int, char>& i : arr2) { if (std::holds_alternative<int>(i)) { std::cout << "int form: " << std::get<0>(i) << '\n'; } else { std::cout << "char form: " << std::get<1>(i) << '\n'; } } return 0; }
9th Feb 2022, 8:56 PM
lona
0
In this case you can use struct that can include different types see JayakrishnašŸ‡®šŸ‡³ answer
10th Feb 2022, 12:44 PM
Yiu 2011