gpt4 book ai didi

c++ - 为什么 std::binary_search 返回 bool?

转载 作者:IT老高 更新时间:2023-10-28 23:18:22 27 4
gpt4 key购买 nike

根据草案N4431 , 函数 std::binary_search在算法库中返回 bool , [binary.search]:

  template<class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last,
const T& value);

template<class ForwardIterator, class T, class Compare>
bool binary_search(ForwardIterator first, ForwardIterator last,
const T& value, Compare comp);

Requires: The elements e of [first,last) are partitioned with respect to the expressions e < value and !(value < e) or comp(e, value) and !comp(value, e). Also, for all elements e of [first,last), e < value implies !(value < e) or comp(e, value) implies !comp(value, e).

Returns: true if there is an iterator i in the range [first,last) that satisfies the corresponding conditions: !(*i < value) && !(value < *i) or comp(*i, value) == false && comp(value, *i) ==
false
.

Complexity: At most log2(last - first) + O(1) comparisons.

有人知道为什么会这样吗?

大多数其他通用算法要么返回元素的迭代器,要么返回与表示元素序列结束的迭代器等效的迭代器(即序列中要考虑的最后一个元素之后的一个),这就是我早就料到了。

最佳答案

这个函数在 1994 版 STL 中的名字是 isMember。我认为您会同意具有该名称的函数应返回 bool

http://www.stepanovpapers.com/Stepanov-The_Standard_Template_Library-1994.pdf

关于c++ - 为什么 std::binary_search 返回 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com