0
Can i add strings in arrays in c++
I just added a string in array by using auto, I got error, please help me to fix it https://code.sololearn.com/cJdYmANdoxdT/?ref=app
11 odpowiedzi
+ 5
Bump it up a bit!
Thanks Ugulberto Sanchez, Bob_Li and Mirielle for bringing up new stuffs (N/A in the lessons) on the table. Many could learn a thing or two from this discussion, including me 👍
Nice discussion for today!
+ 3
EK MUHAMMED FAZIN
auto is not meant to be used that way.
It will be compiled to one type, so it cannot be used in mixed array like in your code.
You could define your own custom mixed type. This way, the array is one type, but that type is a struct composed of many types.
Or you could use std::variant, which is specifically made for this purpose.
here is char, int, double and string in an array.
https://code.sololearn.com/c5FNQQ1Z90Yi/?ref=app
+ 3
Mirielle
any works in Sololearn.😎
Yes, it does seem to work. Great. And it's even simpler😁(if you ignore the big << overload...). Thanks for the tip on using any.
https://code.sololearn.com/ckp2RBwCNAmf/?ref=app
+ 3
EK MUHAMMED FAZIN
Considering the discussion had expanded; may I suggest to update the post title? perhaps "Can I mix string with other types in a C++ array?" makes better relevance ...
It's up to you though ; )
+ 2
Ugulberto Sánchez yes, one datatype is the rule. My arrays are still one type. 🙃
C++ have these strict rules, then gives you convoluted methods to go around them.😁
+ 1
Mirielle
void*😅 I guess people try very hard to bury that beast. It may be out of sight but it's always there.
Updating is like a box of chocolates. You never know what you're gonna get...🙃. I can understand why you hesitate. Updating often breaks stuff.
I've seen a template version of the cout for any in Stack Overflow. Here is the visit_any template applied to ostream <<operator overload.
https://code.sololearn.com/cTfYNR752Glz/?ref=app
+ 1
EK MUHAMMED FAZIN
I hope my codes were helpful in showing you how to create and use mixed type arrays in C++.
They may look complicated, but perhaps they will lead you to explore the C++ std library a little bit deeper.
There are lots of helpful and convenient methods in there that cuts down long boilerplate codes.
I also learned a lot while trying to improve my code, and your topic helped me explore new areas. So I am the one who should be thanking you, instead. 😁
0
مرحبا