c++ - 使用 STL 在 C++ 中进行基本的 binary_search

标签 c++ stl binary-search

我只是在玩一些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/

相关文章:

c++ - c++中使用unordered_map实现哈希表并处理冲突

c++ - STL 嵌套容器取消引用错误

algorithm - 使用搜索和排序的不相交集

c++ - 程序错误 "error C3861: ' copyString' : identifier not found", 请告诉我为什么?

java - Hadoop FairScheduler 的高级内部数据结构和算法?

c++ - 分配嵌套的 STL 容器时使用哪个分配器?

java - 如何将线性搜索转换为二进制搜索?

c - C中的二进制搜索,递归函数只接受长度

c++ - Linux进程间可重入信号量

c++ - 在调试期间,我的程序跳转到最近的 while 语句而不中断或继续 [C++]