我只是在玩一些STL算法。在使用binary_search時,我被卡住了。我已經排序矢量字典&然後我通過編寫我自己的比較函數來運行binary_search。但每次打印的輸出都是「未找到」。然而,我搜索的字符串存在於矢量中。任何幫助,將不勝感激。使用STL的C++中的基本binary_search
這裏是片段:
bool ownComparator(const string &a, const string &b){
return lexicographical_compare(a.begin(),a.end(),b.begin(),b.end());
}
...
...
cout<<"Now using Binary Search to search in sorted array"<<endl;
string searchStr="will";
bool b = binary_search(dictionary.begin(),dictionary.end(),searchStr, ownComparator);
if(b) cout<<"Found";
else cout<<"Not Found";
您是否使用自己的比較器函數對向量排序? – Oswald 2012-08-02 12:31:27
[Ideone](http://ideone.com/0MZGx)正常工作。你確定使用'ownComparator'函數進行排序嗎? – Grizzly 2012-08-02 12:33:33
不,我用過:sort(dictionary.begin(),dictionary.end(),更少()); –
Dominix
2012-08-02 12:33:44