I write a function that should convert a string to a number. I see two possible variants to write it:
int convert(const std::string input) {
if (input == "one") {
return 1;
} else if (input == "two") {
return 2;
}
// etc.
return 0;
}
Or
int convert(const std::string input) {
static const map<string, int> table = {
{"one", 1},
{"two", 2}
// etc.
}
const auto result = table.find(input);
if (result == table.end())
{
return 0;
}
return result->second;
}
What way is more effective/acceptable/readable?
Aucun commentaire:
Enregistrer un commentaire