Jungle camping code coach but with switch | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Jungle camping code coach but with switch

I want to stress I've already solved the exercise completely, but I'm trying to figure out a different way. I'm trying to solve this with a switch statement, but switch doesn't take string values as an input. Assigning independent variables to each string would seem to take more time than is worth it and make the code unnecessarily bulky. Scanning each character and assigning a composite value seems the same, and duplication of values would result in larger cases. Am I wasting my time trying to incorporate switch into a problem like this? I almost feel it should work with the small amount of cases for the problem, but does defining a case into an enumerated type add unnecessary steps?

21st Jun 2020, 2:16 AM
Andrew Mehrle
Andrew Mehrle - avatar
2 ответов
+ 2
You may achieve the same effect of a "switch" by using a hash table, which in C++ is an "unordered_map". A hash table allows items to be indexed via a special key. For this problem, you may use the animal sounds as keys, and their names as values. #include <unordered_map> /* Code snippet: initialization */ unordered_map<string, string> animals; animals["Chirp"] = "Bird"; animals["Ssss"] = "Snake"; animals["Grr"] = "Lion"; animals["Rawr"] = "Tiger"; /* Code snippet: usage */ string input = "Grr"; std::cout << animals[input] << std::endl; Reference: https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/
21st Jun 2020, 3:37 AM
Felipe BF
+ 1
Cool, thanks, especially the link, that helped.
22nd Jun 2020, 2:24 AM
Andrew Mehrle
Andrew Mehrle - avatar