1

The program should be a binary search in a vector. In the end it prints the found element. My code is:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> s{"a","b","c"};

    auto beg=s.begin(), end=s.end(), mid=s.begin()+(end-beg)/2;
    auto sought='c';

    while(*mid!=sought && mid!=end)
    {
        if(*mid>sought)
            end=mid;

        else
                beg=mid+1;

        mid=beg+(end-beg)/2;
    }

    cout<<(*mid)<<endl;
    return 0;
}

It says that the error is that operator != has no match at (*mid!=sought && mid!=end). If I try to do it on a simple string instead of a vector it works.

  • 3
    Btw your condition should have `mid!=end` on the left of `&&`, otherwise you can get UB – Slava Sep 20 '17 at 18:48
  • 1
    And as usual: Don't use "using namespace std". [See here why](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – klutt Sep 20 '17 at 18:55
  • You know std::lower_bound? –  Sep 20 '17 at 20:37

1 Answers1

4

The type of 'c' is char. The type of *mid is std::string. operator!= is not defined between char and std::string.

You can change sought to:

auto sought = "c"; // C-style string

Or to:

using namespace std::literals;
auto sought = "c"s; // `std::string`
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416