Thread: problem with template function

  1. #1
    Registered User
    Join Date
    May 2010

    problem with template function

    can anyone tell me why when i call the binary search function in int main() it tells me it cant match it to the template i have set up?

    #include <iostream>
    #include <vector>
    using namespace std;
    template <typename T>
    T binary_search(vector<T> data, T begin, T end, T searched_value)
       if(begin > end)
          return -1;
       T mid = (begin + end)/2;
       if (data[mid] == searched_value)
     	return mid;
       else if (data[mid] < searched_value)
    	return binary_search(data, mid + 1, end, searched_value);
    	return binary_search(data, begin, mid - 1, searched_value);
    int main()
       vector<int> v;
       cout << "Enter a series of integers: " << "\n";
       int numbers;
       while(cin >> numbers)
       cout << "\n";
       cout << "What integer shall i search for?" << "\n";
       int n;
       cin >> n;
       int pos = binary_search(v, 0, v.size()-1, n);
       cout << "Found in position" << pos << "\n";
      return 0;

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    I would doubt that v.size()-1 is of the same type as the rest, since it's going to be unsigned.

    In addition to the syntax error, you have a huge gaping logic error, since binary_search is going to require sorted data, which you don't have.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Explain: A template function is not a function
    By AnishaKaul in forum C++ Programming
    Replies: 2
    Last Post: 05-13-2010, 10:58 AM
  2. template function v.s. template class
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2007, 12:46 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  4. Template function specialization
    By thomas.behr in forum C++ Programming
    Replies: 4
    Last Post: 06-03-2003, 11:50 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM