1

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

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

#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";
}

为什么我不需要两个向量元素?为什么我只需要一个和第二个d类型的参数()key?到底是什么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

4

2 回答 2

1

的第四个参数是容器中的元素和你的key之间lower_bound的定义。<

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

有了这个,lower_bound只知道数组中<元素(ie)之间的关系,而对元素key{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/
于 2017-03-31T00:42:04.660 回答
0

下限保证它只key作为右手参数传递。

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

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

这仅适用于所有元素ecomp(e,key)位于列表开头的情况。

于 2017-03-30T23:48:28.027 回答