c++ - 比较 50 个以上字符串的有效方法

标签 c++ string c++11

我有一个方法,它采用两个参数,一个作为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 对您来说不够(快),您可以想出某种静态最佳哈希结构,因为键在编译时是已知的。

关于c++ - 比较 50 个以上字符串的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59177728/

相关文章:

c++ - 从 std::regex 中提取原始正则表达式模式

android - 类型转换为 Long

c++ - 定义 std::hash<std::function>

c++ - 虚拟组合键

c++ - 随机数正态分布挂程序?

c++ - 在类构造函数中设置函数指针... '&' : illegal operation on bound member function expression

c++ - 一般获取所有对象的属性 C++

c++ - Xcode 中的预期表达式错误

c++ - 在 C++ 中将字符串作为模板参数传递

c++ - 模板方法和默认模板参数