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

C++ STL: Passing an empty container to lower_bound

是否定义了将空容器传递给 std::lower_bound 的行为?

我查了 cppreference.com 和我在网上找到的旧版本的 C++ 标准,但找不到确切的答案。

cppreference.com documentation for std::deque::erase有句

The iterator first does not need to be dereferenceable if first==last: erasing an empty range is a no-op.

我想念 std::lower_bound 和其他算法的类似内容。

Cppreference 关于 std::lower_bound(first, last) 的 return 值:

"[it returns] Iterator pointing to the first element that is not less than value, or last if no such element is found.".

(强调我的)

在空范围内,将没有满足条件的元素,因此 last 将被 returned。

由此得出结论,在空范围上应用 std::lower_bound(以及类似的)是 明确定义的。它什么都不做, returns last,等于 first.

std::lower_bound 回答了这个问题,“在不违反顺序的情况下,第一个可以插入给定元素的地方(如在什么迭代器值之前)?”如果给定的 [first, last) 范围是空的,那么唯一可以插入任何内容的地方就在 last 之前(等于 first), 所以就是这样 lower_bound returns.

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.

现在:

  1. 空容器的范围[first, last]只有一个成员,即其成员函数返回的迭代器end()
  2. i因此只能end().
  3. 只有一个可行范围[first, i),即[end, end())
  4. 这个范围是空的,因为没有元素大于或等于end()低于然后end() 同时.

由于没有every iteratorj,我猜引用的句子可以改写成:

Returns: [first, last].

范围内的最远迭代器 i

这意味着唯一可以返回的 iend().