简体   繁体   English

C ++ STL:将空容器传递给lower_bound

[英]C++ STL: Passing an empty container to lower_bound

Is the behavior for passing an empty container to std::lower_bound defined? 将空容器传递给std::lower_bound的行为是否已定义?

I checked cppreference.com and an old version of the C++ standard that I found online, but couldn't find a definite answer. 我检查了cppreference.com和我在网上找到的旧版C ++标准,但找不到明确的答案。

The cppreference.com documentation for std::deque::erase has a sentence std::deque::erasecppreference.com文档有一个句子

The iterator first does not need to be dereferenceable if first==last : erasing an empty range is a no-op. 如果first==last ,迭代器首先不需要是可解除引用的:擦除空范围是无操作。

I miss something like this for std::lower_bound and other algorithms. 我想念std::lower_bound和其他算法这样的东西。

Cppreference on the return value of std::lower_bound(first, last) : 关于std::lower_bound(first, last)的返回值的Cppreference

"[it returns] Iterator pointing to the first element that is not less than value, or last if no such element is found . ". “[它返回] Iterator指向不小于value的第一个元素, 如果没有找到这样的元素则指向last元素

(emphasis mine) (强调我的)

In an empty range, there will be no elements that satisfy the criteria, so last will be returned. 在空范围内,将没有符合条件的元素,因此将返回last

Concluding from this, applying std::lower_bound (and similar) on the empty range is well-defined . 由此得出结论,在空范围上应用std::lower_bound (和类似的)是明确定义的 It does nothing and returns last , which is equal to first . 它什么都不做, last返回,等于first

The Standard says : 标准说

Returns: The furthermost iterator i in the range [first, last] such that for every iterator j in the range [first, i) the following corresponding conditions hold: *j < value or comp(*j, value) != false . 返回:最远迭代i在范围[first, last] ,从而使每一迭代j范围[first, i)下列相应条件成立: *j < valuecomp(*j, value) != false

Now: 现在:

  1. The range [first, last] for an empty container has a single member, namely the iterator returned by its member function end() . 空容器的[first, last]范围有一个成员,即由其成员函数end()返回的迭代器。
  2. i can therefore by only end() . 因此i只能end()
  3. There is only one viable range [first, i) , which is [end, end()) . 只有一个可行的范围[first, i) ,即[end, end())
  4. This range is empty, since there is no element that is greater or equal than end() and lower then end() at the same time. 此范围为空,因为没有元素大于或等于 end()并且同时低于 end()

Since there is no every iterator j , I guess the quoted sentence can be rewritten into: 由于没有每个迭代器j ,我猜引用的句子可以重写为:

Returns: The furthermost iterator i in the range [first, last] . 返回: [first, last]范围内最远的迭代器i

Which implies that the only i that can be returned is end() . 这意味着只有i可以返回的是end()

std :: lower_bound回答了这个问题,“Where(就像在迭代器值之前)是第一个可以插入给定元素而不违反排序的地方?”如果给定的[ first,last ]范围为空,则只有在最后一个位置插入任何东西(等于第一个 ),所以这就是lower_bound返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM