Skip to content

Instantly share code, notes, and snippets.

@illescasDaniel
Created November 26, 2016 15:51
Show Gist options
  • Select an option

  • Save illescasDaniel/67bc9ca3b90eec34aa466aadc482c5d7 to your computer and use it in GitHub Desktop.

Select an option

Save illescasDaniel/67bc9ca3b90eec34aa466aadc482c5d7 to your computer and use it in GitHub Desktop.
Switch with strings [C++]
#include <iostream>
#include <map>
#include <vector>
using namespace std;
void setupSwitchWithStrings(vector<string> strings, string& value, map<string,uint16_t>& map);
void toLower(string& str);
int main() {
map<string,uint16_t> mappedString;
string value;
getline(cin,value);
setupSwitchWithStrings({"Bye", "Hi", "John", "How are you?"}, value, mappedString);
enum { bye, hi, john, howAreYou };
switch (mappedString[value]) {
case bye:
cout << "Have a great day!" << endl;
break;
case hi:
cout << "Hello!!" << endl;
break;
case john:
cout << "Nice to meet you!" << endl;
break;
case howAreYou:
cout << "I'm fine!" << endl;
break;
default:
cout << "?" << endl;
break;
}
return 0;
}
void setupSwitchWithStrings(vector<string> strings, string& value, map<string,uint16_t>& map) {
uint16_t idx = 0;
for (string& str: strings) {
toLower(str);
map[str] = idx;
++idx;
}
toLower(value);
}
void toLower(string& str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment