c++ - 了解下限/上限接口(interface)

标签 c++ interface lower-bound

我无法理解下限/上限接口(interface)的语义。

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

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

为什么我不需要两个 vector 元素?为什么我只需要 key 类型的一个和第二个参数 (d)? d 到底是什么?文档听起来像是一个 vector 元素转换为 key 类型。但是为什么不接受另一个 vector 元素作为第二个参数呢?为什么不与 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找不到 key ,因为它不知道要比较的规则!

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/

关于c++ - 了解下限/上限接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130054/

相关文章:

c++ - 玩转 getopt

java - 我完全不知道如何在我的java程序中使用keylistener

C++: map ,键的前一项

scala - 具有上限的函数中类型推断的奇怪行为

c++ - 找到变量定义的任何程序或技巧?

python - 简单的 pybind11 模块失败,没有命名模块

java - 将 "Map<UUID, String>"接口(interface)替换为更简单的 "IMap"

java - 匿名类与实现接口(interface)的编程约定

c++ - 使用带有比较结构的 lower_bound 将对象插入到 vector 中

c++ - 比较类成员数组元素和主要元素