簡體   English   中英

std :: binary_search的自定義比較功能

[英]Custom Compare function for std::binary_search

這段代碼有什么問題嗎?

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;
    }
}

我正在嘗試編寫自己的比較函數以比較BinarySearch中的字符串

我收到以下錯誤:

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>)’

任何幫助表示贊賞...

這段代碼有什么問題嗎?

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

除了它總是返回true嗎? 是的,基本問題是成員函數具有隱式參數this ,因此簽名與預期謂詞的簽名不匹配。 您應該將這個函數static地執行,或者甚至將其作為一個自由函數(如果需要,請與friend )。 另外,您每次都在復制strings ,最好通過const引用獲取參數以避免不必要的復制。

如果謂詞的實際結果取決於Spellcheck對象的狀態,則必須將該狀態綁定到成員函數,以便創建具有適當簽名的函數對象:

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

您正在嘗試傳遞非靜態成員函數,該成員函數不能轉換為所需的二進制函數(由於具有三個實際參數)。

嘗試將您的smart_comp函數聲明為static (當然,您不能引用實例成員;如果需要有狀態,則必須編寫完整的函子。)

假設this->words的類型為std::vector<std::string>並且funcSpellcheck的成員,則可以解決這一smart_comp ,方法是將smart_comp聲明為static 但是我會對您的課堂設計三思而后行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM