如何解决为什么binary_search和find在这里工作不同?
如果我运行以下代码,则会收到错误代码为 prog.cpp:7:39:错误:'operator =='不匹配(操作数类型为'bool'和'std :: vector :: iterator {aka __gnu_cxx :: __ normal_iterator
但是,如果我使用find()而不是binary_search(),则会得到预期的结果。 这两个函数仅返回一个迭代器,但是为什么在这种情况下它们的行为有所不同?
#include <bits/stdc++.h>
using namespace std;
int main ()
{
vector < int >v = { 1,2,3,5 };
if (binary_search (v.begin (),v.end (),3) == v.end ())
cout << "not found";
else
cout << "found";
}
解决方法
std::find
和std::binary_search
做不同的事情。
-
std::find
将迭代器返回到找到的元素(如果找不到,则返回end()
)。它不需要订购范围。 -
std::binary_search
返回bool
,true
或false
。它要求订购范围。
如果您希望将二进制搜索算法和结合起来使用,则可以使用std::lower_bound
,std::upper_bound
或{ {3}}。我将使用std::equal_range
给出一个示例:
#include <algorithm>
#include <iostream>
#include <vector>
int main () {
std::vector v = { 1,2,3,5 };
std::cout << std::boolalpha
<< std::binary_search (v.begin(),v.end(),3) << '\n' // prints true
<< std::binary_search (v.begin(),4) << '\n' // prints false
;
auto[first,last] = std::equal_range(v.begin(),3);
if(first != last) std::cout << "found\n"; // prints found
else std::cout << "not found\n";
for(;first != last; ++first) std::cout << *first << '\n'; // prints 3 twice
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。