将字符串传递给模板函数

时间:2018-10-17 07:04:43

标签: c++ string templates

我使用模板进行通用二进制搜索,但是在字符串情况下,我无法获得结果。我不能只获得字符串类型的结果。 请帮我了解谢谢!

#include <iostream>
#include <string>
using namespace std;

template <class T>
T binarySearch(T arr[], int left, int right, T x)
{
     if(right >= 1)
    {
        int mid = (left + right)/2;
        if(x == arr[mid])
        {
            return mid;
        }
        //right side of array
        else if(x > arr[mid])
        {
            return binarySearch(arr,mid+1,right,x);
        }
        //left side of array
        else
        {
            return binarySearch(arr,left,mid-1,x);
        }
    }
    else
        return -1;
}

int main()
{
     int intArr[11] = {0,1,2,3,4,5,6,7,8,9,10};
     double doubleArr[11] = {1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0};
     string stringArr[11] = {"abc", "bcd", "cde", "def", "efg", "fgh", "ghi", "hij", "ijk", "jkl", "klm"};
     int length = sizeof(intArr)/sizeof(intArr[0]);
     cout << "binarySearch<int>(intArr,0,length,9): " << binarySearch<int>(intArr,0,length,9) << endl;
     cout << "binarySearch<double>(doubleArr,0,length,1.3): " << binarySearch<double>(doubleArr,0,length,1.3) << endl;
     string s = "cdf";
     cout << "binarySearch<string>(stringArr,length,cdf): " << binarySearch<string>(stringArr,0,length,s) << endl;
}

1 个答案:

答案 0 :(得分:2)

我认为您需要将返回类型设为int而不是T。 因为当您使用binarySearch(...)时,返回类型= std :: string。

template <class T>
int binarySearch(T arr[], int left, int right, T x)