2011-11-03 4 views
0

이 코드에 문제가 있습니까? 내가std :: binary_search의 사용자 정의 비교 기능

나는 점점 오전 오류 다음 binarysearch에서 문자열을 비교하는 내 자신의 비교 함수를 작성하는 것을 시도하고있다

bool Spellcheck::smart_comp(string value, string key){ 
    return true; 
} 

void func(){ 
    std::string aprox_key = "hello"; 
    if(std::binary_search(this->words.begin(), this->words.end(), aprox_key, smart_comp)){ 
     std::cout << "Found" << std::endl; 
    } 
} 

: 어떤 도움에 감사드립니다

xyz.cpp:40:85: error: no matching function for call to ‘binary_search(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&, <unresolved overloaded function type>)’ 
xyz.cpp:40:85: note: candidates are: 
/usr/include/c++/4.6/bits/stl_algo.h:2665:5: note: template<class _FIter, class _Tp> bool std::binary_search(_FIter, _FIter, const _Tp&) 
/usr/include/c++/4.6/bits/stl_algo.h:2698:5: note: bool std::binary_search(_FIter, _FIter, const _Tp&, _Compare) [with _FIter = __gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >, _Tp = std::basic_string<char>, _Compare = bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)] 
/usr/include/c++/4.6/bits/stl_algo.h:2698:5: note: no known conversion for argument 4 from ‘<unresolved overloaded function type>’ to ‘bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)’ 

...

답변

4

Is there any problem with this code?

bool Spellcheck::smart_comp(string const value, string const key){ 
    return true; 
} 

항상 그렇지 않으면 true을 반환합니까? 예, 기본 문제는 멤버 함수에 암시 적 매개 변수 this이 있기 때문에 서명이 예상 술어와 일치하지 않습니다. 이 기능은 static이거나 무료 기능 (필요한 경우 friend ed)을 수행해야합니다. 또한 매번 strings을 복사하고 있으므로 불필요한 복사본을 피하기 위해 const 참조로 인수를 취하는 것이 가장 좋습니다.

std::binary_search(
    this->words.begin(), this->words.end() 
    , std::bind(&Spellcheck::smart_comp, this) 
); 
+0

말하자면,이 함수를 클래스 외부에 배치해야합니까? – rda3mon

+1

@ 링고 : 실제로, 그것이 내용물에 의존하지 않는다면. 그렇지 않으면 이러한 상태를 전달하는 함수 객체가 필요합니다. –

+0

고마워요 ... – rda3mon

2
: 술어의 실제 결과는 Spellcheck 객체의 상태에 따라 달라집니다 경우

, 당신은 appropiate 서명 함수 객체를 생성하기 위해 멤버 함수에 그 상태를 결합해야합니다

세 개의 실제 매개 변수가 인 계정에서 필요한 이진 함수로 변환 할 수없는 비 정적 멤버 함수를 전달하려고합니다.

smart_comp 함수 static을 신고 해보세요. (물론 당신은 인스턴스 멤버를 참조 할 수 없습니다, 당신은 statefulness을 필요로하는 경우, 당신은 전체 펑터를 작성해야합니다.) this->words의 유형 std::vector<std::string>func입니다 가정

1

Spellcheck의 구성원, 당신이 할 수있는 smart_compstatic이라고 선언 할 때 주변에서 작업하십시오. 그러나 나는 당신의 수업 설계에 대해 두 번 생각할 것입니다.

+0

왜 내 수업 설계에 결함이 있다고 생각합니까? 다른 점에 동의합니다. – rda3mon

+0

@ 링고 : 비교 논리를 stateful functor가 아닌 다른 클래스에 넣을 분명한 이유가 없기 때문입니다. – ildjarn

+0

확인. 실수로 배우기. – rda3mon

관련 문제