我只是在玩一些STL算法。在使用 binary_search 时我陷入困境。我已经对 vector 字典进行了排序,然后我通过编写自己的比较器函数来运行binary_search。然而,每次打印的输出都是“未找到”。然而,我搜索的字符串存在于 vector 中。任何帮助将不胜感激。
这是片段:
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";
最佳答案
得到了解决方案:当我使用字符串 searchStr="will\r"; 进行搜索时它说发现意味着在从文件中读取时,逐行读取到 vector 中,并将\r 附加到字符串中。嗯,愚蠢的错误。
关于c++ - 使用 STL 在 C++ 中进行基本的 binary_search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11777387/