【问题标题】:understanding the lower bound/ upper bound interface理解下限/上限接口
【发布时间】:2017-03-31 09:07:27
【问题描述】:

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

考虑一下我写的这个测试sn-p:

#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吗?

【问题讨论】:

    标签: c++ interface lower-bound


    【解决方案1】:

    lower_bound 的第四个参数是&lt; 在容器中的元素 和您的key 之间的定义。

    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&lt;int&gt;})之间的&lt; 关系,但对 element 之间的关系一无所知键。因此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/

    【讨论】:

      【解决方案2】:

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

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

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

      这仅适用于所有元素 e 使得 comp(e,key) 位于列表的开头。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 2016-05-20
        • 2010-12-21
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多