Beach Williams
Beach Williams

Reputation: 153

No match for operator "!=" (c++ iterators)

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.

Upvotes: 1

Views: 261

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

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`

Upvotes: 4

Related Questions