c++ - 为什么 binary_search() 和 find() 在这里的工作方式不同?
问题描述
如果我运行以下代码,我会得到错误prog.cpp:7:39: error: no match for 'operator==' (operand types are 'bool' and 'std::vector::iterator {aka __gnu_cxx: :__normal_iterator<int , std::vector >}') if(binary_search(v.begin(),v.end(),3) == v.end()) cout<<"未找到"; *
但是如果我使用 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
或std::equal_range
. 我将举一个例子std::equal_range
:
#include <algorithm>
#include <iostream>
#include <vector>
int main () {
std::vector v = { 1, 2, 3, 3, 5 };
std::cout << std::boolalpha
<< std::binary_search (v.begin(), v.end(), 3) << '\n' // prints true
<< std::binary_search (v.begin(), v.end(), 4) << '\n' // prints false
;
auto[first, last] = std::equal_range(v.begin(), v.end(), 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
}
推荐阅读
- laravel-6 - count():参数必须是数组或对象,在 Laravel 6 和 php 7.2+ 中实现了 Countable
- html - 我很难在我的网站上的图像下将标题居中
- angular - 如何以编程方式隐藏 ngx-toaster?
- pytorch - RuntimeError:只有浮点 dtype 的张量才能需要渐变
- java - 如何使用 toString 方法在第三个对象中打印两个对象?
- date - 谷歌电子表格 - 谷歌脚本中两个日期之间的工作日数,节假日除外
- git - mac OS catalina 上的 git clone 命令面临问题
- sql - 使用 SQL Server 对学生成绩进行排序
- java - 从 Redis 获取密钥
- php - 文件链接在本地主机 http://127.0.0.1:8000 上的 laravel 中不可用