【问题标题】:Binary Search on a std::string array在 std::string 数组上进行二分搜索
【发布时间】:2016-08-04 18:43:09
【问题描述】:

下面是代码和

std::string str[5] = {"Tejas","Mejas","Rajas","Pojas","Ljas"};
std::sort(str,str+5);
size_t test =  bin_search("Ljas",str,5);

这里是二分查找的通用函数

 template<class T>
    size_t bin_search(T x,  T* array, int  n)
     {
     size_t begin = 0, end = n;
            // Invariant: This function will eventually return a value in      the range [begin, end]
             while (begin != end) {
                       size_t mid = (begin + end) / 2;
                       if (array[mid] < x) {
                              begin = mid + 1;
                       } else {
                                 end = mid;
                       }
      }
     return begin;   // Or return end, because begin == end
}

错误是

 main.cpp|12|error: no matching function for call to 'bin_search(const char [5], std::string [5], int)'|

只有std::string 数组有问题,但int 数组工作得很好。 它适用于字符串数组还是逻辑中缺少任何东西?

【问题讨论】:

    标签: c++ arrays string templates c++11


    【解决方案1】:

    正如错误消息试图告诉你的那样,"Ljas" 不是std::string,而是const char[5]。然后template argument deduction 失败,因为无法推断出T 类型(如const char*std::string)。

    您可以将其显式转换为 std::string 以使模板参数推导正常工作:

    size_t test =  bin_search(std::string("Ljas"),str,5);
    

    或显式指定模板参数以避免模板参数推导:

    size_t test =  bin_search<std::string>("Ljas",str,5);
    

    【讨论】:

      【解决方案2】:
      template<class T>
      size_t bin_search(T x,  T* array, int  n)
      

      期望你收到一个 T 和一个指向 T 的指针。当编译器扣除类型时

      size_t test =  bin_search("Ljas",str,5);
      

      x 被推断为const char[5],因为所有字符串文字都具有const char[N] 类型。 array 推导出std::strign[5]。由于 cont char[]std::string[] 不是同一类型,因此将生成 no 函数。您需要将"Ljas" 设为类似

      的字符串
      size_t test =  bin_search(std::string("Ljas"),str,5);
      

      还要注意传递给二分搜索的集合需要排序。如果数据未排序,那么您无法推断元素应该在哪一半。

      【讨论】:

        【解决方案3】:

        size_t test = bin_search(std::string("Ljas"), str, 5); 可能吗?

        【讨论】:

          【解决方案4】:
          • 即使您修复了编译错误,您的算法也不会工作,因为二进制搜索需要一个排序数组。
          • 不必编写自己的二分查找算法,STL 已经有一个:http://en.cppreference.com/w/cpp/algorithm/binary_search
          • 您的第一个参数应该是 std::string,而不是字符串文字:bin_search(std::string("Ljas"),str,5);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-12-25
            • 1970-01-01
            • 2023-03-17
            • 2015-12-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-21
            相关资源
            最近更新 更多