了解下限/上限接口
understanding the lower bound/ upper 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";
}
为什么我不需要两个矢量元素?为什么我只需要一个和第二个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 代码的信息。
- http://www.cplusplus.com/reference/algorithm/lower_bound/
下限保证它只通过key
作为右手参数。
它进行二分搜索,寻找comp(e,key)
从真变为假的地方。 如果它在特定元素e
comp(e,key)
为真,则搜索后面的元素,如果为假,则搜索前面的元素,直到找到元素"kess than"键和元素"大于"键之间的"边缘"。 它通过二叉搜索来做到这一点:所以首先是迭代器范围的中间,然后是它接下来要搜索的范围中间,递归。
然后,它将迭代器返回到最早的元素e
以便!comp(e,key)
为真。
仅当所有元素都e
,comp(e,key)
位于列表的开头时,这才有效。
相关文章:
- 正在尝试了解输入验证循环
- 了解 GLM- openGL 中的相机转换
- C++我需要了解在哪里使用指针和双指针
- 如何深入了解明显的腐败
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Visual C++GC接口如何启用它以及要包含哪个库
- Windows.h与GLFW.h的接口
- 了解嵌套循环打印星号图案
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 提供与TMP和SFINAE的通用接口
- 为重写std::exception的库生成swig接口时出错
- 内联如何影响模块接口中的成员函数
- COM 接口 c# 封送数组数组
- 如何在 SCIP C++ 接口中获取 MILP 约束矩阵中的系数值
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 了解每月第一天函数的代码
- 了解C++标准::shared_ptr
- 如何绑定 C++ gRPC 客户端的网络接口
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 了解下限/上限接口