I'm supposed to rewrite a binary search function so that it uses a generic type for array elements instead of just int. The only changes I made to the function are inserting the line "template<typename T>" and changing the line "int binarySearch(const int list[], int key, int arraySize)" to "int binarySearch(const T list[], T key, int arraySize)". So this is what I have:

#include <iostream>
using namespace std;

template<typename T>
int binarySearch(const T list[], T key, int arraySize)
{
    int low = 0;
    int high = arraySize - 1;
    while (high >= low)
    {
          int mid = (low + high) / 2;
          if (key < list[mid])
             high = mid - 1;
          else if (key == list[mid])
             return mid;
          else
             low = mid + 1;
    }
    
    return -1;
}

int main()
{
    int intList[] = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
    double doubleList[] = {2.1, 4.2, 7.3, 10.4, 11.5, 45.6, 50.7, 59.8, 60.9, 66.10, 69.11, 70.12, 79.13};
    string stringList[] = {"abc","mno","xyz"};
    
    cout << binarySearch(intList, 2, 13) << endl;
    cout << binarySearch(doubleList, 59.8, 13) << endl;
    cout << binarySearch(stringList, "mno", 5) << endl;

    system("PAUSE");
    return 0;
}

I have to test it on arrays with int, double, and string values, and so far I can get it to work for the first two types of arrays, but I can't get it to work for string arrays. I keep getting the error "31: no matching function for call to `binarySearch(std::string[3], const char[4], int)' ". I don't know what to do about this. Can anyone help?

Recommended Answers

All 2 Replies

First of all you should include the header <string>.Secondly the function must be declared like this

template <typename C,typename T> function (C , T , int);

It worked. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.