了解下限/上限接口

understanding the lower bound/ upper bound interface

本文关键字:接口 了解      更新时间:2023-10-16

我无法掌握下限/上限接口的语义。

考虑一下我写的这个测试片段:

#include <algorithm>
#include <iostream>
#include <vector>
int main() {
  // sorted vector
  std::vector<std::pair<size_t, std::vector<int>>> v = {
      std::make_pair(0, std::vector<int>()),
      std::make_pair(0, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(5, std::vector<int>()),
      std::make_pair(20, std::vector<int>())};
  auto key = 3;
  auto itr = std::lower_bound(
      v.begin(), v.end(), key,
      [](const auto &t1, const size_t d) -> bool { return t1.first < d; });
  std::cout << itr->first << "n";
}

为什么我不需要两个矢量元素?为什么我只需要一个和第二个key类型的参数(d(?d到底是什么?文档听起来像是转换为key类型的矢量元素。但是为什么不接受另一个向量元素作为第二个参数呢?为什么没有与key进行比较?

为什么界面不是这样的:

auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});

你能解释一下参数背后的语义吗,尤其是d

lower_bound的第 4 个参数是容器中的元素之间的<定义。

auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});

这样,lower_bound只知道元素之间的<关系(即 {int, vector<int>} ( 在数组中,但对元素之间的关系一无所知。因此,lower_bound找不到密钥,因为它只是不知道要比较的规则

d在这里作为key传递,即 每次都3进行比较。它等于

auto it = std::lower_bound(
    v.begin(), v.end(), key,
    [key](const auto &t1, const size_t whatever) -> bool { return t1.first < key; }
);

查看更多关于 cplusplus.com 代码的信息。


  1. http://www.cplusplus.com/reference/algorithm/lower_bound/

下限保证它只通过key作为右手参数。

它进行二分搜索,寻找comp(e,key)从真变为假的地方。 如果它在特定元素e comp(e,key)为真,则搜索后面的元素,如果为假,则搜索前面的元素,直到找到元素"kess than"键和元素"大于"键之间的"边缘"。 它通过二叉搜索来做到这一点:所以首先是迭代器范围的中间,然后是它接下来要搜索的范围中间,递归。

然后,它将迭代器返回到最早的元素e以便!comp(e,key)为真。

仅当所有元素都ecomp(e,key)位于列表的开头时,这才有效。