Что не так с предикатом binary_search в моем коде

0

Я читал о binary_search, а затем я попытался реализовать его с помощью предиката. Вот мой код (я также включил предикат сортировки, который я использую). Я знаю, что меньше, чем по умолчанию. Это грубый тестовый код

class person
{
public:
    int age;
};

//sort predicate
class less_than_key
{
public:
    inline bool operator()(const person& pa , const person& pb)
    {
        return (pa.age < pb.age);
    }
};

//Binary Search predicate
class bsearch_predicate
{
    public:
    bool operator()(const person& pa)
    {
        return pa.age == n;
    }
    bsearch_predicate(int i):n(i) {}
    int n;
};

Реализация

    person p;
p.age = 24;

std::vector<person> vec;
vec.push_back(p);

std::sort(vec.begin(),vec.end(),less_than_key());

std::binary_search(vec.begin(),vec.end(),bsearch_predicate(24));

Теперь binary_search здесь дает ошибку, однако, если я попробую это с std :: find_if как таковой

std::find_if(vec.begin(),vec.end(),bsearch_predicate(24));

Вышеупомянутые работы. Я был бы признателен, если бы кто-то мог сказать мне, почему я получаю ошибки компоновщика с std :: binary_search из моего кода. Ошибки компоновщика:

Error   12  error C2676: binary '<' : 'const bsearch_predicate' does not define this operator or a conversion to a type acceptable to the predefined operator   d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   4   error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const bsearch_predicate'  d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   10  error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const bsearch_predicate' d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   7   error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const bsearch_predicate'  d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   3   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const bsearch_predicate'    d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   5   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const bsearch_predicate'  d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   1   error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const bsearch_predicate' d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   2   error C2784: 'bool std::operator <(const std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::move_iterator<_RanIt> &' from 'const bsearch_predicate'    d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   11  error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const bsearch_predicate'   d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   9   error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const bsearch_predicate'   d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   8   error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const bsearch_predicate' d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Error   6   error C2784: 'bool std::operator <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : could not deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const bsearch_predicate'   d:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm    2978    1
Теги:
stl

1 ответ

2
Лучший ответ

Функция binary_search не принимает оператор равенства, но итератор неравенства, который определяет порядок. Вы должны моделировать предикат, как если бы это было меньше, чем сравнение.

Причина в том, что алгоритм binary_search должен знать об относительном порядке аргумента и элементе, на котором он binary_search решить, в каком направлении продолжить поиск. Элемент считается найденным, когда ни pred(*it,value) ни pred(value,*it) являются истинными (если ни одно значение не меньше другого, они одинаковы)

  • 0
    Мой предикат уже делает меньше, чем сравнение? Я что-то здесь упускаю?
  • 2
    @Rajeshwar: Нет, вы не: bool bsearch_predicate::operator()(const person& pa){ return pa.age == n;} В основном вам нужно использовать тот же предикат для binary_search который вы передали для sort .
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню