I need to know of how to use switch with string.I know that we can use if and else instead. But I want to know of how to use string directly with switch.
#include <iostream>
#include <map>
int main()
{
std::map<std::string, std::string> m;
m["apple"] = "grows on trees";
m["lion"] = "a big cat";
m["turkey"] = "a bird and a country";
m["guitar"] = "an instrument";
std::string str;
std::cin >> str;
std::map<std::string, std::string>::iterator it;
it = m.find(str);
if (it != m.end())
{
std::cout << it->second << std::endl;
}
else
{
std::cout << "not sure what that is" << std::endl;
}
}
The above works fine when you only want to to lookup a value of a certain type but if you want different functionality in each case it's a bit more complicated. One way is to use a mix of switch and map, by having a map that lookup a value that you can use in the switch.
#include <iostream>
#include <map>
enumclass Word // If you don't use C++11 or later you can use a normal enum
{
apple,
lion,
turkey,
guitar
};
int main()
{
std::map<std::string, Word> m;
m["apple"] = Word::apple;
m["lion"] = Word::lion;
m["turkey"] = Word::turkey;
m["guitar"] = Word::guitar;
std::string str;
std::cin >> str;
std::map<std::string, Word>::iterator it;
it = m.find(str);
if (it != m.end())
{
switch (it->second)
{
case Word::apple:
// Do something
break;
case Word::lion:
// Do something else
break;
case Word::turkey:
// ...
break;
case Word::guitar:
// ...
break;
}
}
else
{
std::cout << "not sure what that is" << std::endl;
}
}
Another approach is to let the map map to a std::function of some kind and use lambda functions to set them conveniently. If you don't use C++11 you can get the same functionality by defining normal functions and having function pointers in the map.