0

I am trying to implement a method of binary search that uses vector::iterators as it's a main driver for recursive calls.

So far I have:

template<typename T, typename iter> 
vector<int>::iterator binary_search(iter low, iter high, T key) {
    if (high < low) return -1;

    iter median = distance(low, high) / 2;

    if (*median == key) 
        return median;

    else if (*median > key) 
        return binary_search(low, median - 1, key);

    return binary_search(median + 1 , high, key);
}

But I receive the compiler errors:

  • 'binary_search': ambiguous call to overloaded function
  • more than one instance of overloaded function "binary_search" matches the argument list

with the call

vector<int> nums = { 0,1,2,3,4,5,6,7,8,9 };
binary_search(nums.begin(), nums.end(), 1);

Besides that, if you happen to catch something else faulty, please let me know! Thanks in advance.

onesiumus
  • 279
  • 6
  • 26
  • You do realize that there is a [std::binary_search](http://en.cppreference.com/w/cpp/algorithm/binary_search) algorithm function in the `std::` namespace? So maybe you don't need to write your own binary search, as it already exists. If not that, you also have [std::lower_bound](http://en.cppreference.com/w/cpp/algorithm/lower_bound) – PaulMcKenzie Sep 03 '16 at 01:31
  • 1
    Also, please post a [mcve]. This way others can reproduce the compiler error and give you the exact reason why there is an error. My belief is that you have `using namespace std;` and the compiler sees both`std::binary_search` and your version of `binary_search`, thus the error. – PaulMcKenzie Sep 03 '16 at 01:39
  • Yeah, I understand that. I am writing this for my own practice. @paul, will do – onesiumus Sep 03 '16 at 01:39
  • 2
    My advice is to not name your functions with the same name as standard functions. Also, if you go to the links I posted, you should see an implementation of such function, using real code. Then compare what you're doing with what the implementation shows you. – PaulMcKenzie Sep 03 '16 at 01:41
  • 1
    May be worth a look (using namespace std) https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – Galik Sep 03 '16 at 05:46

1 Answers1

0

As @ PaulMcKenzie suggested, the error had occurred because I was writing under the std namespace, along with the algorithm header that includes std::binary_search.

onesiumus
  • 279
  • 6
  • 26