Is there any technical reason why std::lower_bound is not specialized for red-black tree iterators?

前端 未结 5 881
走了就别回头了
走了就别回头了 2020-12-06 09:26

I have always assumed that std::lower_bound() runs in logarithmic time if I pass a pair of red-black tree iterators (set::iterator or map::it

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 09:56

    There are multiple reasons:

    1. When using the non-member version a different predicate can be used. In fact, a different predicate has to be used when using, e.g., a std::map as the map predicate operates on Ks while the range operates on pairs of K and V.
    2. Even if the predicate is compatible, the function has an interface using a pair of nodes somewhere in the tree rather than the root node which would be needed for an efficient search. Although it is likely that there are parent pointers, requiring so for the tree seems inappropriate.
    3. The iterators provided to the algorithm are not required to be the t.begin() and the t.end() of the tree. They can be somewhere in the tree, making the use of the tree structure potentially inefficient.
    4. The standard library doesn't have a tree abstraction or algorithms operating on trees. Although the associative ordered containers are [probably] implemented using trees the corresponding algorithms are not exposed for general use.

    The part I consider questionable is the use of a generic name for an algorithm which has linear complexity with bidirectional iterators and logarithmic complexity with random access iterators (I understand that the number of comparisons has logarithmic complexity in both cases and that the movements are considered to be fast).

提交回复
热议问题