gpt4 book ai didi

c++ - 查询 std::binary_search()

转载 作者:行者123 更新时间:2023-11-28 00:06:09 24 4
gpt4 key购买 nike

我目前正在考虑使用 std::binary_search()(来自库)来确定列表中是否存在某个实例。在我开始使用它之前,我想知道它是如何工作的。

我的理解是它使用比较(对于用户定义的结构/类,它需要访问用户定义的比较函数)来查明对象的实例是否存在于列表/vector 中。根据这个网站 ( http://www.cplusplus.com/reference/algorithm/binary_search/ ),使用的范围是:

[first, last)

所以它不是包括 last 因为它必须将 lastlast + 1 进行比较吗?

此外,用户定义的比较函数的逻辑并不重要,只要它能区分对象/类中的属性即可。对吗?

例如,如果我的结构/类包含以下内容:

coord
{
int X;
int Y;
}

我必须确保我的比较函数区分(以某种方式,例如大于/小于比较)列表/vector 中元素 a 和 b 的 X 和 Y 属性。

最佳答案

std::binary_search() 被实现为一种常见的二进制搜索算法,它最多执行 log2(N)+1 次元素比较。 (有关如何实现二进制搜索的更多信息,请查看 link )

So is it not including last because it would have to compare last against last + 1?

不是,只是为了方便使用。您可以将函数调用为:

std::binary_search (v.begin(), v.end(), 42)

注意 v.end() 返回一个迭代器到序列末尾之后的元素。因此,它不指向任何元素,因此不应在搜索中进行评估。

Also the user-defined compare function's logic does not matter as long as it differentiates between properties within the object/class. Is that correct?

它用于 binary_search() 的比较函数是为了知道您要查找的元素是在当前正在测试的元素之前还是之后。换句话说,比较函数必须能够比较两个元素并在第一个元素“低于”第二个元素时返回(必须在第二个元素之前放置在容器中)。

对于您的 Coord 示例,您可以编写一个比较器函数,例如:

struct lessThanKey
{
inline bool operator() (const Coord& lhs, const Coord& rhs)
{
return (lhs.x < rhs.x) || ((lhs.x == rhs.x) && (lhs.y < rhs.y));
}
};

std::binary_search(v.begin(), v.end(), Coord{42, 42}, lessThanKey());

关于c++ - 查询 std::binary_search(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642101/

24 4 0
文章推荐: css - 如何使链接仅在访问后改变颜色
文章推荐: html - 样式标签导致头部错误
文章推荐: html -

标签脱离了它的

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com