我有采用两个参数一个作为string
和另一个作为的方法int
。
该字符串必须与50个以上的字符串进行比较,一旦找到匹配项,则需要使用硬编码字符串映射int值,如下例所示
例如:
string Compare_Method(std::string str, int val) {
if(str == "FIRST")
{
std::array<std::string, 3> real_value = {"Hello1","hai1","bye1"}
return real_value[val];
}
else if(str == "SECOND")
{
std::array<std::string, 4> real_value = {"Hello2","hai2","bye2"}
return real_value[val];
}
else if(str == "THIRD")
{
std::array<std::string, 5> real_value = {"Hello3","hai3","bye3"}
return real_value[val];
}
//----- 50+ else if
}
我的方法如上所述。什么是有效的方法
1.比较50个以上的字符串。
2.为每个if案例创建std :: array
编辑:std :: array大小不固定,可以是上面编辑的3、4、5。
这就是我这样做的方式。数据结构仅创建一次,访问时间应足够快
#include <iostream>
#include <string>
#include <array>
#include <unordered_map>
std::string Compare_Method(const std::string& str, int val)
{
// or std::vector<std::string>
static std::unordered_map<std::string, std::array<std::string, 3>> map
{
{ "FIRST", { "Hello1", "hail1", "bye1" }},
{ "SECOND", { "Hello2", "hail2", "bye2" }},
{ "THIRD", { "Hello3", "hail3", "bye3" }},
// 50+ more
};
// maybe check if str is present in the map
return map[str][val];
}
int main()
{
std::cout << Compare_Method("SECOND", 1) << std::endl;
}
如果std::unordered_map
不够(快速),那么您可以提出某种静态的最佳哈希结构,因为键是在编译时知道的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句