std::lower_bound与std::set::lower_bound的区别

Discrepencies between std::lower_bound and std::set::lower_bound

本文关键字:std bound lower 区别 set      更新时间:2023-10-16

c++草案说std::lower_bound:

§ 25.4.3.1 lower_bound [lower.bound]  
template<class ForwardIterator, class T>  
ForwardIterator lower_bound(ForwardIterator first, 
                            ForwardIterator last, 
                            const T& value);  
template<class ForwardIterator, class T, class Compare>  
ForwardIterator lower_bound(ForwardIterator first, 
                            ForwardIterator last, 
                            const T& value, 
                            Compare comp);  
Requires: The elements e of [first,last) shall be partitioned with respect 
    to the expression e < value or comp(e, value).
Returns: The furthermost iterator i in the range [first,last] such that for 
    any iterator j in the range [first,i) the following corresponding 
    conditions hold: *j < value or comp(*j, value) != false.
Complexity: At most log2(last − first) + O(1) comparisons.

注意,这允许(通过暗示)比较与*ForwardIterator返回的不同(但可比较)的类型,但对迭代器推进的数量没有复杂性限制。(对于基于节点的容器,这将是O(last - first)迭代器进度。)

§ 23.4.6.1
class set { 
   ...
    iterator lower_bound(const key_type& x);
    const_iterator lower_bound(const key_type& x) const;
   ...
}

标准没有详细说明这些函数,但它暗示这些函数用于O(log2(last - first))比较和推进,但要求搜索键与包含的类型相同。

我的问题是:
(1)是否有办法获得std::set::lower_bound的速度和std::lower_bound的搜索类型的灵活性?
(2)为什么std::lower_bound不需要专门用于std::set::iterator ?
(3)是否存在std::lower_bound 专门用于std::set::iterator的实现,或者有不这样做的原因?

我希望找到这样的东西:

template< class Key, class Comp, class Alloc, class Lookup>  
std::set<Key, Compare, Alloc>::const_iterator 
    lower_bound(
        std::set<Key, Comp, Alloc>::const_iterator begin, 
        std::set<Key, Comp, Alloc>::const_iterator end, 
        const Lookup& find,
        Compare comp);
template< class Key, class Comp, class Alloc, class Lookup>  
std::set<Key, Compare, Alloc>::iterator 
    lower_bound(
        std::set<Key, Comp, Alloc>::iterator begin, 
        std::set<Key, Comp, Alloc>::iterator end, 
        const Lookup& find,
        Compare comp);

或:

template < class Key, class Compare = less<Key>, class Allocator = allocator<Key> >
class set {
   ...
    template<class Lookup>
    iterator lower_bound(const Lookup& x);
    template<class Lookup>
    const_iterator lower_bound(const Lookup& x) const;
   ...
}

但我怀疑它是否存在。显然,所有这些都可以扩展到其他基于树的容器和其他算法。我会自己编写代码,但这需要我使用特定于实现的代码。这个想法来自于这个问题:在非键类型

的集合中进行有效搜索

根据构造时给出的比较对象对std::set容器进行排序。当调用std::lower_bound时,没有办法检查它是否传递了一个匹配的比较对象,因此实现无法知道是使用标准算法还是专门用于集合的算法,因为后者仅在使用用于集合排序的比较对象(或给出相同结果的比较对象)时有效。

您添加的两个示例原型不起作用:

  1. std::lower_bound专化为std::set迭代器:

    由于上面给出的原因,这不起作用:没有办法检查给定的比较对象是否与set的构造函数中给定的比较对象匹配。你的原型只检查比较对象的类型是否匹配,但可以有相同类型的不同比较对象。

  2. std::set::lower_bound接受模板参数:

    这可能使它与set的比较对象不兼容,因为该对象的operator()通常不会被模板化,并且只期望T类型的参数。