|
|
|
|
int: 5 double: 1.7 string: Hello |
Why give you advice when you'll just delete the question after you've hoovered up the free help, impetus. |
An array can only hold values of one type. Usually if you want multiple types you'd use a struct: struct mydata { int i {}; double d {}; std::string s; }; mydata myarray[] {{0, 1.1, "qwe"}, {1, 3.3, "asd"}}; |
Peter87 (10193) Statically typed languages like C++ doesn't make such things so easy. Consider if there is another way to go about it where you don't have to store different types in the same container. That said, C++17 introduced std::variant which is designed to store one of many different types. std::vector<std::variant<int, double, std::string>> list; list.push_back(5); list.push_back(1.7); list.push_back("Hello"); for (const std::variant<int, double, std::string>& e : list) { if (const int* int_ptr = std::get_if<int>(&e)) { std::cout << "int: " << *int_ptr << "\n"; } else if (const double* dbl_ptr = std::get_if<double>(&e)) { std::cout << "double: " << *dbl_ptr << "\n"; } else if (const std::string* str_ptr = std::get_if<std::string>(&e)) { std::cout << "string: " << *str_ptr << "\n"; } } |
But what is maximum item quanity to be held by struct? I need about 12 items, mix ints and doubles, two or three strings... |
impetus wrote: |
---|
Class is not an option |
Hi folks! Could you advise the array type to contain both ints, doubles and strings. Class is not an option Struct might be fine! But what is maximum item quanity to be held by struct? I need about 12 items, mix ints and doubles, two or three strings... Thanks! This one looks familiar to QVariant, which is perfect for some cases, but you actually can not easy get std string for example.. I will test both 1) struct and 2) C++ variant and update here. I hope it has simplicity and power of simple vector of array |