c – partition_point和lower_bound有什么区别?
作者:互联网
C 11包括算法std::partition_point()
.然而,对于我尝试过的所有情况,它给出与std::lower_bound()
相同的答案.唯一的区别是方便的T&值参数.
我错过了什么,或者这两个功能或多或少都做了同样的事情?
解决方法:
它们基本相同.这将是lower_bound的有效实现:
template <typename ForwardIterator, typename T>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
T const& value)
{
return partition_point(first, last, [&](auto&& elem) {
return elem < value;
});
}
template <typename ForwardIterator, typename T, typename Compare>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
T const& value, Compare comp)
{
return partition_point(first, last, [&](auto&& elem) {
return comp(elem, value);
});
}
这两种算法依赖于查找分区范围的分区点,它们只需要使用不同的参数进行搜索(对于partition_point的一元谓词,对于lower_bound的值或值和二进制谓词).
我们通常只考虑带有二元谓词的排序范围上下文中的lower_bound – 即使相对于这样的谓词的完全排序范围是not a requirement for that algorithm.
当我们在它的时候,upper_bound也可以用partition_point实现,只是操作数被翻转而谓词被否定:
template <typename ForwardIterator, typename T>
ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last,
T const& value)
{
return partition_point(first, last, [&](auto&& elem) {
return !(value < elem);
});
}
template <typename ForwardIterator, typename T, typename Compare>
ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last,
T const& value, Compare comp)
{
return partition_point(first, last, [&](auto&& elem) {
return !comp(value, elem);
});
}
这两个措辞有多么不同,这有点奇怪.
lower_bound
returns(上限措辞为similar):
The furthermost iterator
i
in the range[first, last]
such that for every iteratorj
in the range[first, i)
the following corresponding conditions hold:*j < value
orcomp(*j, value) != false
.
An iterator
mid
such thatall_of(first, mid, pred)
andnone_of(mid, last, pred)
are bothtrue
.
这些短语是等价的,因为要求是范围是分区的.但乍看之下肯定不是这样.
标签:c,c11,binary-search,std,partitioning 来源: https://codeday.me/bug/20190910/1801496.html