我需要一个与 C + + STL 容器兼容的二进制搜索算法,类似于标准库 <algorithm>
头中的 std::binary_search
,但是我需要它返回指向结果的迭代器,而不是一个简单的布尔告诉我元素是否存在。
(顺便说一句,当标准委员会为二进制搜索定义 API 时,他们到底是怎么想的?)
My main concern here is that I need the speed of a binary search, so although I can find the data with other algorithms, as mentioned below, I want to take advantage of the fact that my data is sorted to get the benefits of a binary search, not a linear search.
到目前为止,如果数据丢失,lower_bound
和 upper_bound
就会失败:
//lousy pseudo code
vector(1,2,3,4,6,7,8,9,0) //notice no 5
iter = lower_bound_or_upper_bound(start,end,5)
iter != 5 && iter !=end //not returning end as usual, instead it'll return 4 or 6
注意: 我也可以使用不属于 std 名称空间的算法,只要它与容器兼容。比如说 boost::binary_search
。