xref: /llvm-project-15.0.7/libcxx/include/__tree (revision 2df59c50)
1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___TREE
11#define _LIBCPP___TREE
12
13#include <__config>
14#include <iterator>
15#include <memory>
16#include <stdexcept>
17#include <algorithm>
18
19#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
20#pragma GCC system_header
21#endif
22
23_LIBCPP_PUSH_MACROS
24#include <__undef_macros>
25
26
27_LIBCPP_BEGIN_NAMESPACE_STD
28
29#if defined(__GNUC__) && !defined(__clang__) // gcc.gnu.org/PR37804
30template <class, class, class, class> class _LIBCPP_TEMPLATE_VIS map;
31template <class, class, class, class> class _LIBCPP_TEMPLATE_VIS multimap;
32template <class, class, class> class _LIBCPP_TEMPLATE_VIS set;
33template <class, class, class> class _LIBCPP_TEMPLATE_VIS multiset;
34#endif
35
36template <class _Tp, class _Compare, class _Allocator> class __tree;
37template <class _Tp, class _NodePtr, class _DiffType>
38    class _LIBCPP_TEMPLATE_VIS __tree_iterator;
39template <class _Tp, class _ConstNodePtr, class _DiffType>
40    class _LIBCPP_TEMPLATE_VIS __tree_const_iterator;
41
42template <class _Pointer> class __tree_end_node;
43template <class _VoidPtr> class __tree_node_base;
44template <class _Tp, class _VoidPtr> class __tree_node;
45
46template <class _Key, class _Value>
47struct __value_type;
48
49template <class _Allocator> class __map_node_destructor;
50template <class _TreeIterator> class _LIBCPP_TEMPLATE_VIS __map_iterator;
51template <class _TreeIterator> class _LIBCPP_TEMPLATE_VIS __map_const_iterator;
52
53/*
54
55_NodePtr algorithms
56
57The algorithms taking _NodePtr are red black tree algorithms.  Those
58algorithms taking a parameter named __root should assume that __root
59points to a proper red black tree (unless otherwise specified).
60
61Each algorithm herein assumes that __root->__parent_ points to a non-null
62structure which has a member __left_ which points back to __root.  No other
63member is read or written to at __root->__parent_.
64
65__root->__parent_ will be referred to below (in comments only) as end_node.
66end_node->__left_ is an externably accessible lvalue for __root, and can be
67changed by node insertion and removal (without explicit reference to end_node).
68
69All nodes (with the exception of end_node), even the node referred to as
70__root, have a non-null __parent_ field.
71
72*/
73
74// Returns:  true if __x is a left child of its parent, else false
75// Precondition:  __x != nullptr.
76template <class _NodePtr>
77inline _LIBCPP_INLINE_VISIBILITY
78bool
79__tree_is_left_child(_NodePtr __x) _NOEXCEPT
80{
81    return __x == __x->__parent_->__left_;
82}
83
84// Determines if the subtree rooted at __x is a proper red black subtree.  If
85//    __x is a proper subtree, returns the black height (null counts as 1).  If
86//    __x is an improper subtree, returns 0.
87template <class _NodePtr>
88unsigned
89__tree_sub_invariant(_NodePtr __x)
90{
91    if (__x == nullptr)
92        return 1;
93    // parent consistency checked by caller
94    // check __x->__left_ consistency
95    if (__x->__left_ != nullptr && __x->__left_->__parent_ != __x)
96        return 0;
97    // check __x->__right_ consistency
98    if (__x->__right_ != nullptr && __x->__right_->__parent_ != __x)
99        return 0;
100    // check __x->__left_ != __x->__right_ unless both are nullptr
101    if (__x->__left_ == __x->__right_ && __x->__left_ != nullptr)
102        return 0;
103    // If this is red, neither child can be red
104    if (!__x->__is_black_)
105    {
106        if (__x->__left_ && !__x->__left_->__is_black_)
107            return 0;
108        if (__x->__right_ && !__x->__right_->__is_black_)
109            return 0;
110    }
111    unsigned __h = __tree_sub_invariant(__x->__left_);
112    if (__h == 0)
113        return 0;  // invalid left subtree
114    if (__h != __tree_sub_invariant(__x->__right_))
115        return 0;  // invalid or different height right subtree
116    return __h + __x->__is_black_;  // return black height of this node
117}
118
119// Determines if the red black tree rooted at __root is a proper red black tree.
120//    __root == nullptr is a proper tree.  Returns true is __root is a proper
121//    red black tree, else returns false.
122template <class _NodePtr>
123bool
124__tree_invariant(_NodePtr __root)
125{
126    if (__root == nullptr)
127        return true;
128    // check __x->__parent_ consistency
129    if (__root->__parent_ == nullptr)
130        return false;
131    if (!__tree_is_left_child(__root))
132        return false;
133    // root must be black
134    if (!__root->__is_black_)
135        return false;
136    // do normal node checks
137    return __tree_sub_invariant(__root) != 0;
138}
139
140// Returns:  pointer to the left-most node under __x.
141// Precondition:  __x != nullptr.
142template <class _NodePtr>
143inline _LIBCPP_INLINE_VISIBILITY
144_NodePtr
145__tree_min(_NodePtr __x) _NOEXCEPT
146{
147    while (__x->__left_ != nullptr)
148        __x = __x->__left_;
149    return __x;
150}
151
152// Returns:  pointer to the right-most node under __x.
153// Precondition:  __x != nullptr.
154template <class _NodePtr>
155inline _LIBCPP_INLINE_VISIBILITY
156_NodePtr
157__tree_max(_NodePtr __x) _NOEXCEPT
158{
159    while (__x->__right_ != nullptr)
160        __x = __x->__right_;
161    return __x;
162}
163
164// Returns:  pointer to the next in-order node after __x.
165// Precondition:  __x != nullptr.
166template <class _NodePtr>
167_NodePtr
168__tree_next(_NodePtr __x) _NOEXCEPT
169{
170    if (__x->__right_ != nullptr)
171        return __tree_min(__x->__right_);
172    while (!__tree_is_left_child(__x))
173        __x = __x->__parent_unsafe();
174    return __x->__parent_unsafe();
175}
176
177template <class _EndNodePtr, class _NodePtr>
178inline _LIBCPP_INLINE_VISIBILITY
179_EndNodePtr
180__tree_next_iter(_NodePtr __x) _NOEXCEPT
181{
182    if (__x->__right_ != nullptr)
183        return static_cast<_EndNodePtr>(__tree_min(__x->__right_));
184    while (!__tree_is_left_child(__x))
185        __x = __x->__parent_unsafe();
186    return static_cast<_EndNodePtr>(__x->__parent_);
187}
188
189// Returns:  pointer to the previous in-order node before __x.
190// Precondition:  __x != nullptr.
191// Note: __x may be the end node.
192template <class _NodePtr, class _EndNodePtr>
193inline _LIBCPP_INLINE_VISIBILITY
194_NodePtr
195__tree_prev_iter(_EndNodePtr __x) _NOEXCEPT
196{
197    if (__x->__left_ != nullptr)
198        return __tree_max(__x->__left_);
199    _NodePtr __xx = static_cast<_NodePtr>(__x);
200    while (__tree_is_left_child(__xx))
201        __xx = __xx->__parent_unsafe();
202    return __xx->__parent_unsafe();
203}
204
205// Returns:  pointer to a node which has no children
206// Precondition:  __x != nullptr.
207template <class _NodePtr>
208_NodePtr
209__tree_leaf(_NodePtr __x) _NOEXCEPT
210{
211    while (true)
212    {
213        if (__x->__left_ != nullptr)
214        {
215            __x = __x->__left_;
216            continue;
217        }
218        if (__x->__right_ != nullptr)
219        {
220            __x = __x->__right_;
221            continue;
222        }
223        break;
224    }
225    return __x;
226}
227
228// Effects:  Makes __x->__right_ the subtree root with __x as its left child
229//           while preserving in-order order.
230// Precondition:  __x->__right_ != nullptr
231template <class _NodePtr>
232void
233__tree_left_rotate(_NodePtr __x) _NOEXCEPT
234{
235    _NodePtr __y = __x->__right_;
236    __x->__right_ = __y->__left_;
237    if (__x->__right_ != nullptr)
238        __x->__right_->__set_parent(__x);
239    __y->__parent_ = __x->__parent_;
240    if (__tree_is_left_child(__x))
241        __x->__parent_->__left_ = __y;
242    else
243        __x->__parent_unsafe()->__right_ = __y;
244    __y->__left_ = __x;
245    __x->__set_parent(__y);
246}
247
248// Effects:  Makes __x->__left_ the subtree root with __x as its right child
249//           while preserving in-order order.
250// Precondition:  __x->__left_ != nullptr
251template <class _NodePtr>
252void
253__tree_right_rotate(_NodePtr __x) _NOEXCEPT
254{
255    _NodePtr __y = __x->__left_;
256    __x->__left_ = __y->__right_;
257    if (__x->__left_ != nullptr)
258        __x->__left_->__set_parent(__x);
259    __y->__parent_ = __x->__parent_;
260    if (__tree_is_left_child(__x))
261        __x->__parent_->__left_ = __y;
262    else
263        __x->__parent_unsafe()->__right_ = __y;
264    __y->__right_ = __x;
265    __x->__set_parent(__y);
266}
267
268// Effects:  Rebalances __root after attaching __x to a leaf.
269// Precondition:  __root != nulptr && __x != nullptr.
270//                __x has no children.
271//                __x == __root or == a direct or indirect child of __root.
272//                If __x were to be unlinked from __root (setting __root to
273//                  nullptr if __root == __x), __tree_invariant(__root) == true.
274// Postcondition: __tree_invariant(end_node->__left_) == true.  end_node->__left_
275//                may be different than the value passed in as __root.
276template <class _NodePtr>
277void
278__tree_balance_after_insert(_NodePtr __root, _NodePtr __x) _NOEXCEPT
279{
280    __x->__is_black_ = __x == __root;
281    while (__x != __root && !__x->__parent_unsafe()->__is_black_)
282    {
283        // __x->__parent_ != __root because __x->__parent_->__is_black == false
284        if (__tree_is_left_child(__x->__parent_unsafe()))
285        {
286            _NodePtr __y = __x->__parent_unsafe()->__parent_unsafe()->__right_;
287            if (__y != nullptr && !__y->__is_black_)
288            {
289                __x = __x->__parent_unsafe();
290                __x->__is_black_ = true;
291                __x = __x->__parent_unsafe();
292                __x->__is_black_ = __x == __root;
293                __y->__is_black_ = true;
294            }
295            else
296            {
297                if (!__tree_is_left_child(__x))
298                {
299                    __x = __x->__parent_unsafe();
300                    __tree_left_rotate(__x);
301                }
302                __x = __x->__parent_unsafe();
303                __x->__is_black_ = true;
304                __x = __x->__parent_unsafe();
305                __x->__is_black_ = false;
306                __tree_right_rotate(__x);
307                break;
308            }
309        }
310        else
311        {
312            _NodePtr __y = __x->__parent_unsafe()->__parent_->__left_;
313            if (__y != nullptr && !__y->__is_black_)
314            {
315                __x = __x->__parent_unsafe();
316                __x->__is_black_ = true;
317                __x = __x->__parent_unsafe();
318                __x->__is_black_ = __x == __root;
319                __y->__is_black_ = true;
320            }
321            else
322            {
323                if (__tree_is_left_child(__x))
324                {
325                    __x = __x->__parent_unsafe();
326                    __tree_right_rotate(__x);
327                }
328                __x = __x->__parent_unsafe();
329                __x->__is_black_ = true;
330                __x = __x->__parent_unsafe();
331                __x->__is_black_ = false;
332                __tree_left_rotate(__x);
333                break;
334            }
335        }
336    }
337}
338
339// Precondition:  __root != nullptr && __z != nullptr.
340//                __tree_invariant(__root) == true.
341//                __z == __root or == a direct or indirect child of __root.
342// Effects:  unlinks __z from the tree rooted at __root, rebalancing as needed.
343// Postcondition: __tree_invariant(end_node->__left_) == true && end_node->__left_
344//                nor any of its children refer to __z.  end_node->__left_
345//                may be different than the value passed in as __root.
346template <class _NodePtr>
347void
348__tree_remove(_NodePtr __root, _NodePtr __z) _NOEXCEPT
349{
350    // __z will be removed from the tree.  Client still needs to destruct/deallocate it
351    // __y is either __z, or if __z has two children, __tree_next(__z).
352    // __y will have at most one child.
353    // __y will be the initial hole in the tree (make the hole at a leaf)
354    _NodePtr __y = (__z->__left_ == nullptr || __z->__right_ == nullptr) ?
355                    __z : __tree_next(__z);
356    // __x is __y's possibly null single child
357    _NodePtr __x = __y->__left_ != nullptr ? __y->__left_ : __y->__right_;
358    // __w is __x's possibly null uncle (will become __x's sibling)
359    _NodePtr __w = nullptr;
360    // link __x to __y's parent, and find __w
361    if (__x != nullptr)
362        __x->__parent_ = __y->__parent_;
363    if (__tree_is_left_child(__y))
364    {
365        __y->__parent_->__left_ = __x;
366        if (__y != __root)
367            __w = __y->__parent_unsafe()->__right_;
368        else
369            __root = __x;  // __w == nullptr
370    }
371    else
372    {
373        __y->__parent_unsafe()->__right_ = __x;
374        // __y can't be root if it is a right child
375        __w = __y->__parent_->__left_;
376    }
377    bool __removed_black = __y->__is_black_;
378    // If we didn't remove __z, do so now by splicing in __y for __z,
379    //    but copy __z's color.  This does not impact __x or __w.
380    if (__y != __z)
381    {
382        // __z->__left_ != nulptr but __z->__right_ might == __x == nullptr
383        __y->__parent_ = __z->__parent_;
384        if (__tree_is_left_child(__z))
385            __y->__parent_->__left_ = __y;
386        else
387            __y->__parent_unsafe()->__right_ = __y;
388        __y->__left_ = __z->__left_;
389        __y->__left_->__set_parent(__y);
390        __y->__right_ = __z->__right_;
391        if (__y->__right_ != nullptr)
392            __y->__right_->__set_parent(__y);
393        __y->__is_black_ = __z->__is_black_;
394        if (__root == __z)
395            __root = __y;
396    }
397    // There is no need to rebalance if we removed a red, or if we removed
398    //     the last node.
399    if (__removed_black && __root != nullptr)
400    {
401        // Rebalance:
402        // __x has an implicit black color (transferred from the removed __y)
403        //    associated with it, no matter what its color is.
404        // If __x is __root (in which case it can't be null), it is supposed
405        //    to be black anyway, and if it is doubly black, then the double
406        //    can just be ignored.
407        // If __x is red (in which case it can't be null), then it can absorb
408        //    the implicit black just by setting its color to black.
409        // Since __y was black and only had one child (which __x points to), __x
410        //   is either red with no children, else null, otherwise __y would have
411        //   different black heights under left and right pointers.
412        // if (__x == __root || __x != nullptr && !__x->__is_black_)
413        if (__x != nullptr)
414            __x->__is_black_ = true;
415        else
416        {
417            //  Else __x isn't root, and is "doubly black", even though it may
418            //     be null.  __w can not be null here, else the parent would
419            //     see a black height >= 2 on the __x side and a black height
420            //     of 1 on the __w side (__w must be a non-null black or a red
421            //     with a non-null black child).
422            while (true)
423            {
424                if (!__tree_is_left_child(__w))  // if x is left child
425                {
426                    if (!__w->__is_black_)
427                    {
428                        __w->__is_black_ = true;
429                        __w->__parent_unsafe()->__is_black_ = false;
430                        __tree_left_rotate(__w->__parent_unsafe());
431                        // __x is still valid
432                        // reset __root only if necessary
433                        if (__root == __w->__left_)
434                            __root = __w;
435                        // reset sibling, and it still can't be null
436                        __w = __w->__left_->__right_;
437                    }
438                    // __w->__is_black_ is now true, __w may have null children
439                    if ((__w->__left_  == nullptr || __w->__left_->__is_black_) &&
440                        (__w->__right_ == nullptr || __w->__right_->__is_black_))
441                    {
442                        __w->__is_black_ = false;
443                        __x = __w->__parent_unsafe();
444                        // __x can no longer be null
445                        if (__x == __root || !__x->__is_black_)
446                        {
447                            __x->__is_black_ = true;
448                            break;
449                        }
450                        // reset sibling, and it still can't be null
451                        __w = __tree_is_left_child(__x) ?
452                                    __x->__parent_unsafe()->__right_ :
453                                    __x->__parent_->__left_;
454                        // continue;
455                    }
456                    else  // __w has a red child
457                    {
458                        if (__w->__right_ == nullptr || __w->__right_->__is_black_)
459                        {
460                            // __w left child is non-null and red
461                            __w->__left_->__is_black_ = true;
462                            __w->__is_black_ = false;
463                            __tree_right_rotate(__w);
464                            // __w is known not to be root, so root hasn't changed
465                            // reset sibling, and it still can't be null
466                            __w = __w->__parent_unsafe();
467                        }
468                        // __w has a right red child, left child may be null
469                        __w->__is_black_ = __w->__parent_unsafe()->__is_black_;
470                        __w->__parent_unsafe()->__is_black_ = true;
471                        __w->__right_->__is_black_ = true;
472                        __tree_left_rotate(__w->__parent_unsafe());
473                        break;
474                    }
475                }
476                else
477                {
478                    if (!__w->__is_black_)
479                    {
480                        __w->__is_black_ = true;
481                        __w->__parent_unsafe()->__is_black_ = false;
482                        __tree_right_rotate(__w->__parent_unsafe());
483                        // __x is still valid
484                        // reset __root only if necessary
485                        if (__root == __w->__right_)
486                            __root = __w;
487                        // reset sibling, and it still can't be null
488                        __w = __w->__right_->__left_;
489                    }
490                    // __w->__is_black_ is now true, __w may have null children
491                    if ((__w->__left_  == nullptr || __w->__left_->__is_black_) &&
492                        (__w->__right_ == nullptr || __w->__right_->__is_black_))
493                    {
494                        __w->__is_black_ = false;
495                        __x = __w->__parent_unsafe();
496                        // __x can no longer be null
497                        if (!__x->__is_black_ || __x == __root)
498                        {
499                            __x->__is_black_ = true;
500                            break;
501                        }
502                        // reset sibling, and it still can't be null
503                        __w = __tree_is_left_child(__x) ?
504                                    __x->__parent_unsafe()->__right_ :
505                                    __x->__parent_->__left_;
506                        // continue;
507                    }
508                    else  // __w has a red child
509                    {
510                        if (__w->__left_ == nullptr || __w->__left_->__is_black_)
511                        {
512                            // __w right child is non-null and red
513                            __w->__right_->__is_black_ = true;
514                            __w->__is_black_ = false;
515                            __tree_left_rotate(__w);
516                            // __w is known not to be root, so root hasn't changed
517                            // reset sibling, and it still can't be null
518                            __w = __w->__parent_unsafe();
519                        }
520                        // __w has a left red child, right child may be null
521                        __w->__is_black_ = __w->__parent_unsafe()->__is_black_;
522                        __w->__parent_unsafe()->__is_black_ = true;
523                        __w->__left_->__is_black_ = true;
524                        __tree_right_rotate(__w->__parent_unsafe());
525                        break;
526                    }
527                }
528            }
529        }
530    }
531}
532
533// node traits
534
535
536#ifndef _LIBCPP_CXX03_LANG
537template <class _Tp>
538struct __is_tree_value_type_imp : false_type {};
539
540template <class _Key, class _Value>
541struct __is_tree_value_type_imp<__value_type<_Key, _Value>> : true_type {};
542
543template <class ..._Args>
544struct __is_tree_value_type : false_type {};
545
546template <class _One>
547struct __is_tree_value_type<_One> : __is_tree_value_type_imp<typename __uncvref<_One>::type> {};
548#endif
549
550template <class _Tp>
551struct __tree_key_value_types {
552  typedef _Tp key_type;
553  typedef _Tp __node_value_type;
554  typedef _Tp __container_value_type;
555  static const bool __is_map = false;
556
557  _LIBCPP_INLINE_VISIBILITY
558  static key_type const& __get_key(_Tp const& __v) {
559    return __v;
560  }
561  _LIBCPP_INLINE_VISIBILITY
562  static __container_value_type const& __get_value(__node_value_type const& __v) {
563    return __v;
564  }
565  _LIBCPP_INLINE_VISIBILITY
566  static __container_value_type* __get_ptr(__node_value_type& __n) {
567    return _VSTD::addressof(__n);
568  }
569#ifndef _LIBCPP_CXX03_LANG
570  _LIBCPP_INLINE_VISIBILITY
571  static __container_value_type&& __move(__node_value_type& __v) {
572    return _VSTD::move(__v);
573  }
574#endif
575};
576
577template <class _Key, class _Tp>
578struct __tree_key_value_types<__value_type<_Key, _Tp> > {
579  typedef _Key                                         key_type;
580  typedef _Tp                                          mapped_type;
581  typedef __value_type<_Key, _Tp>                      __node_value_type;
582  typedef pair<const _Key, _Tp>                        __container_value_type;
583  typedef __container_value_type                       __map_value_type;
584  static const bool __is_map = true;
585
586  _LIBCPP_INLINE_VISIBILITY
587  static key_type const&
588  __get_key(__node_value_type const& __t) {
589    return __t.__get_value().first;
590  }
591
592  template <class _Up>
593  _LIBCPP_INLINE_VISIBILITY
594  static typename enable_if<__is_same_uncvref<_Up, __container_value_type>::value,
595      key_type const&>::type
596  __get_key(_Up& __t) {
597    return __t.first;
598  }
599
600  _LIBCPP_INLINE_VISIBILITY
601  static __container_value_type const&
602  __get_value(__node_value_type const& __t) {
603    return __t.__get_value();
604  }
605
606  template <class _Up>
607  _LIBCPP_INLINE_VISIBILITY
608  static typename enable_if<__is_same_uncvref<_Up, __container_value_type>::value,
609      __container_value_type const&>::type
610  __get_value(_Up& __t) {
611    return __t;
612  }
613
614  _LIBCPP_INLINE_VISIBILITY
615  static __container_value_type* __get_ptr(__node_value_type& __n) {
616    return _VSTD::addressof(__n.__get_value());
617  }
618
619#ifndef _LIBCPP_CXX03_LANG
620  _LIBCPP_INLINE_VISIBILITY
621  static pair<key_type&&, mapped_type&&> __move(__node_value_type& __v) {
622    return __v.__move();
623  }
624#endif
625};
626
627template <class _VoidPtr>
628struct __tree_node_base_types {
629  typedef _VoidPtr                                               __void_pointer;
630
631  typedef __tree_node_base<__void_pointer>                      __node_base_type;
632  typedef typename __rebind_pointer<_VoidPtr, __node_base_type>::type
633                                                             __node_base_pointer;
634
635  typedef __tree_end_node<__node_base_pointer>                  __end_node_type;
636  typedef typename __rebind_pointer<_VoidPtr, __end_node_type>::type
637                                                             __end_node_pointer;
638#if defined(_LIBCPP_ABI_TREE_REMOVE_NODE_POINTER_UB)
639  typedef __end_node_pointer __parent_pointer;
640#else
641  typedef typename conditional<
642      is_pointer<__end_node_pointer>::value,
643        __end_node_pointer,
644        __node_base_pointer>::type __parent_pointer;
645#endif
646
647private:
648  static_assert((is_same<typename pointer_traits<_VoidPtr>::element_type, void>::value),
649                  "_VoidPtr does not point to unqualified void type");
650};
651
652template <class _Tp, class _AllocPtr, class _KVTypes = __tree_key_value_types<_Tp>,
653         bool = _KVTypes::__is_map>
654struct __tree_map_pointer_types {};
655
656template <class _Tp, class _AllocPtr, class _KVTypes>
657struct __tree_map_pointer_types<_Tp, _AllocPtr, _KVTypes, true> {
658  typedef typename _KVTypes::__map_value_type   _Mv;
659  typedef typename __rebind_pointer<_AllocPtr, _Mv>::type
660                                                       __map_value_type_pointer;
661  typedef typename __rebind_pointer<_AllocPtr, const _Mv>::type
662                                                 __const_map_value_type_pointer;
663};
664
665template <class _NodePtr, class _NodeT = typename pointer_traits<_NodePtr>::element_type>
666struct __tree_node_types;
667
668template <class _NodePtr, class _Tp, class _VoidPtr>
669struct __tree_node_types<_NodePtr, __tree_node<_Tp, _VoidPtr> >
670    : public __tree_node_base_types<_VoidPtr>,
671             __tree_key_value_types<_Tp>,
672             __tree_map_pointer_types<_Tp, _VoidPtr>
673{
674  typedef __tree_node_base_types<_VoidPtr> __base;
675  typedef __tree_key_value_types<_Tp>      __key_base;
676  typedef __tree_map_pointer_types<_Tp, _VoidPtr> __map_pointer_base;
677public:
678
679  typedef typename pointer_traits<_NodePtr>::element_type       __node_type;
680  typedef _NodePtr                                              __node_pointer;
681
682  typedef _Tp                                                 __node_value_type;
683  typedef typename __rebind_pointer<_VoidPtr, __node_value_type>::type
684                                                      __node_value_type_pointer;
685  typedef typename __rebind_pointer<_VoidPtr, const __node_value_type>::type
686                                                __const_node_value_type_pointer;
687#if defined(_LIBCPP_ABI_TREE_REMOVE_NODE_POINTER_UB)
688  typedef typename __base::__end_node_pointer __iter_pointer;
689#else
690  typedef typename conditional<
691      is_pointer<__node_pointer>::value,
692        typename __base::__end_node_pointer,
693        __node_pointer>::type __iter_pointer;
694#endif
695private:
696    static_assert(!is_const<__node_type>::value,
697                "_NodePtr should never be a pointer to const");
698    static_assert((is_same<typename __rebind_pointer<_VoidPtr, __node_type>::type,
699                          _NodePtr>::value), "_VoidPtr does not rebind to _NodePtr.");
700};
701
702template <class _ValueTp, class _VoidPtr>
703struct __make_tree_node_types {
704  typedef typename __rebind_pointer<_VoidPtr, __tree_node<_ValueTp, _VoidPtr> >::type
705                                                                        _NodePtr;
706  typedef __tree_node_types<_NodePtr> type;
707};
708
709// node
710
711template <class _Pointer>
712class __tree_end_node
713{
714public:
715    typedef _Pointer pointer;
716    pointer __left_;
717
718    _LIBCPP_INLINE_VISIBILITY
719    __tree_end_node() _NOEXCEPT : __left_() {}
720};
721
722template <class _VoidPtr>
723class __tree_node_base
724    : public __tree_node_base_types<_VoidPtr>::__end_node_type
725{
726    typedef __tree_node_base_types<_VoidPtr> _NodeBaseTypes;
727
728public:
729    typedef typename _NodeBaseTypes::__node_base_pointer pointer;
730    typedef typename _NodeBaseTypes::__parent_pointer __parent_pointer;
731
732    pointer          __right_;
733    __parent_pointer __parent_;
734    bool __is_black_;
735
736    _LIBCPP_INLINE_VISIBILITY
737    pointer __parent_unsafe() const { return static_cast<pointer>(__parent_);}
738
739    _LIBCPP_INLINE_VISIBILITY
740    void __set_parent(pointer __p) {
741        __parent_ = static_cast<__parent_pointer>(__p);
742    }
743
744private:
745  ~__tree_node_base() _LIBCPP_EQUAL_DELETE;
746  __tree_node_base(__tree_node_base const&) _LIBCPP_EQUAL_DELETE;
747  __tree_node_base& operator=(__tree_node_base const&) _LIBCPP_EQUAL_DELETE;
748};
749
750template <class _Tp, class _VoidPtr>
751class __tree_node
752    : public __tree_node_base<_VoidPtr>
753{
754public:
755    typedef _Tp __node_value_type;
756
757    __node_value_type __value_;
758
759private:
760  ~__tree_node() _LIBCPP_EQUAL_DELETE;
761  __tree_node(__tree_node const&) _LIBCPP_EQUAL_DELETE;
762  __tree_node& operator=(__tree_node const&) _LIBCPP_EQUAL_DELETE;
763};
764
765
766template <class _Allocator>
767class __tree_node_destructor
768{
769    typedef _Allocator                                      allocator_type;
770    typedef allocator_traits<allocator_type>                __alloc_traits;
771
772public:
773    typedef typename __alloc_traits::pointer                pointer;
774private:
775    typedef __tree_node_types<pointer> _NodeTypes;
776    allocator_type& __na_;
777
778    __tree_node_destructor& operator=(const __tree_node_destructor&);
779
780public:
781    bool __value_constructed;
782
783    _LIBCPP_INLINE_VISIBILITY
784    explicit __tree_node_destructor(allocator_type& __na, bool __val = false) _NOEXCEPT
785        : __na_(__na),
786          __value_constructed(__val)
787        {}
788
789    _LIBCPP_INLINE_VISIBILITY
790    void operator()(pointer __p) _NOEXCEPT
791    {
792        if (__value_constructed)
793            __alloc_traits::destroy(__na_, _NodeTypes::__get_ptr(__p->__value_));
794        if (__p)
795            __alloc_traits::deallocate(__na_, __p, 1);
796    }
797
798    template <class> friend class __map_node_destructor;
799};
800
801#if _LIBCPP_STD_VER > 14
802template <class _NodeType, class _Alloc>
803struct __generic_container_node_destructor;
804template <class _Tp, class _VoidPtr, class _Alloc>
805struct __generic_container_node_destructor<__tree_node<_Tp, _VoidPtr>, _Alloc>
806    : __tree_node_destructor<_Alloc>
807{
808    using __tree_node_destructor<_Alloc>::__tree_node_destructor;
809};
810#endif
811
812template <class _Tp, class _NodePtr, class _DiffType>
813class _LIBCPP_TEMPLATE_VIS __tree_iterator
814{
815    typedef __tree_node_types<_NodePtr>                     _NodeTypes;
816    typedef _NodePtr                                        __node_pointer;
817    typedef typename _NodeTypes::__node_base_pointer        __node_base_pointer;
818    typedef typename _NodeTypes::__end_node_pointer         __end_node_pointer;
819    typedef typename _NodeTypes::__iter_pointer             __iter_pointer;
820    typedef pointer_traits<__node_pointer> __pointer_traits;
821
822    __iter_pointer __ptr_;
823
824public:
825    typedef bidirectional_iterator_tag                     iterator_category;
826    typedef _Tp                                            value_type;
827    typedef _DiffType                                      difference_type;
828    typedef value_type&                                    reference;
829    typedef typename _NodeTypes::__node_value_type_pointer pointer;
830
831    _LIBCPP_INLINE_VISIBILITY __tree_iterator() _NOEXCEPT
832#if _LIBCPP_STD_VER > 11
833    : __ptr_(nullptr)
834#endif
835    {}
836
837    _LIBCPP_INLINE_VISIBILITY reference operator*() const
838        {return __get_np()->__value_;}
839    _LIBCPP_INLINE_VISIBILITY pointer operator->() const
840        {return pointer_traits<pointer>::pointer_to(__get_np()->__value_);}
841
842    _LIBCPP_INLINE_VISIBILITY
843    __tree_iterator& operator++() {
844      __ptr_ = static_cast<__iter_pointer>(
845          __tree_next_iter<__end_node_pointer>(static_cast<__node_base_pointer>(__ptr_)));
846      return *this;
847    }
848    _LIBCPP_INLINE_VISIBILITY
849    __tree_iterator operator++(int)
850        {__tree_iterator __t(*this); ++(*this); return __t;}
851
852    _LIBCPP_INLINE_VISIBILITY
853    __tree_iterator& operator--() {
854      __ptr_ = static_cast<__iter_pointer>(__tree_prev_iter<__node_base_pointer>(
855          static_cast<__end_node_pointer>(__ptr_)));
856      return *this;
857    }
858    _LIBCPP_INLINE_VISIBILITY
859    __tree_iterator operator--(int)
860        {__tree_iterator __t(*this); --(*this); return __t;}
861
862    friend _LIBCPP_INLINE_VISIBILITY
863        bool operator==(const __tree_iterator& __x, const __tree_iterator& __y)
864        {return __x.__ptr_ == __y.__ptr_;}
865    friend _LIBCPP_INLINE_VISIBILITY
866        bool operator!=(const __tree_iterator& __x, const __tree_iterator& __y)
867        {return !(__x == __y);}
868
869private:
870    _LIBCPP_INLINE_VISIBILITY
871    explicit __tree_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
872    _LIBCPP_INLINE_VISIBILITY
873    explicit __tree_iterator(__end_node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
874    _LIBCPP_INLINE_VISIBILITY
875    __node_pointer __get_np() const { return static_cast<__node_pointer>(__ptr_); }
876    template <class, class, class> friend class __tree;
877    template <class, class, class> friend class _LIBCPP_TEMPLATE_VIS __tree_const_iterator;
878    template <class> friend class _LIBCPP_TEMPLATE_VIS __map_iterator;
879    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS map;
880    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS multimap;
881    template <class, class, class> friend class _LIBCPP_TEMPLATE_VIS set;
882    template <class, class, class> friend class _LIBCPP_TEMPLATE_VIS multiset;
883};
884
885template <class _Tp, class _NodePtr, class _DiffType>
886class _LIBCPP_TEMPLATE_VIS __tree_const_iterator
887{
888    typedef __tree_node_types<_NodePtr>                     _NodeTypes;
889    typedef typename _NodeTypes::__node_pointer             __node_pointer;
890    typedef typename _NodeTypes::__node_base_pointer        __node_base_pointer;
891    typedef typename _NodeTypes::__end_node_pointer         __end_node_pointer;
892    typedef typename _NodeTypes::__iter_pointer             __iter_pointer;
893    typedef pointer_traits<__node_pointer> __pointer_traits;
894
895    __iter_pointer __ptr_;
896
897public:
898    typedef bidirectional_iterator_tag                           iterator_category;
899    typedef _Tp                                                  value_type;
900    typedef _DiffType                                            difference_type;
901    typedef const value_type&                                    reference;
902    typedef typename _NodeTypes::__const_node_value_type_pointer pointer;
903
904    _LIBCPP_INLINE_VISIBILITY __tree_const_iterator() _NOEXCEPT
905#if _LIBCPP_STD_VER > 11
906    : __ptr_(nullptr)
907#endif
908    {}
909
910private:
911    typedef __tree_iterator<value_type, __node_pointer, difference_type>
912                                                           __non_const_iterator;
913public:
914    _LIBCPP_INLINE_VISIBILITY
915    __tree_const_iterator(__non_const_iterator __p) _NOEXCEPT
916        : __ptr_(__p.__ptr_) {}
917
918    _LIBCPP_INLINE_VISIBILITY reference operator*() const
919        {return __get_np()->__value_;}
920    _LIBCPP_INLINE_VISIBILITY pointer operator->() const
921        {return pointer_traits<pointer>::pointer_to(__get_np()->__value_);}
922
923    _LIBCPP_INLINE_VISIBILITY
924    __tree_const_iterator& operator++() {
925      __ptr_ = static_cast<__iter_pointer>(
926          __tree_next_iter<__end_node_pointer>(static_cast<__node_base_pointer>(__ptr_)));
927      return *this;
928    }
929
930    _LIBCPP_INLINE_VISIBILITY
931    __tree_const_iterator operator++(int)
932        {__tree_const_iterator __t(*this); ++(*this); return __t;}
933
934    _LIBCPP_INLINE_VISIBILITY
935    __tree_const_iterator& operator--() {
936      __ptr_ = static_cast<__iter_pointer>(__tree_prev_iter<__node_base_pointer>(
937          static_cast<__end_node_pointer>(__ptr_)));
938      return *this;
939    }
940
941    _LIBCPP_INLINE_VISIBILITY
942    __tree_const_iterator operator--(int)
943        {__tree_const_iterator __t(*this); --(*this); return __t;}
944
945    friend _LIBCPP_INLINE_VISIBILITY
946        bool operator==(const __tree_const_iterator& __x, const __tree_const_iterator& __y)
947        {return __x.__ptr_ == __y.__ptr_;}
948    friend _LIBCPP_INLINE_VISIBILITY
949        bool operator!=(const __tree_const_iterator& __x, const __tree_const_iterator& __y)
950        {return !(__x == __y);}
951
952private:
953    _LIBCPP_INLINE_VISIBILITY
954    explicit __tree_const_iterator(__node_pointer __p) _NOEXCEPT
955        : __ptr_(__p) {}
956    _LIBCPP_INLINE_VISIBILITY
957    explicit __tree_const_iterator(__end_node_pointer __p) _NOEXCEPT
958        : __ptr_(__p) {}
959    _LIBCPP_INLINE_VISIBILITY
960    __node_pointer __get_np() const { return static_cast<__node_pointer>(__ptr_); }
961
962    template <class, class, class> friend class __tree;
963    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS map;
964    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS multimap;
965    template <class, class, class> friend class _LIBCPP_TEMPLATE_VIS set;
966    template <class, class, class> friend class _LIBCPP_TEMPLATE_VIS multiset;
967    template <class> friend class _LIBCPP_TEMPLATE_VIS __map_const_iterator;
968
969};
970
971template<class _Tp, class _Compare>
972#ifndef _LIBCPP_CXX03_LANG
973    _LIBCPP_DIAGNOSE_WARNING(!std::__invokable<_Compare const&, _Tp const&, _Tp const&>::value,
974        "the specified comparator type does not provide a const call operator")
975#endif
976int __diagnose_non_const_comparator();
977
978template <class _Tp, class _Compare, class _Allocator>
979class __tree
980{
981public:
982    typedef _Tp                                      value_type;
983    typedef _Compare                                 value_compare;
984    typedef _Allocator                               allocator_type;
985
986private:
987    typedef allocator_traits<allocator_type>         __alloc_traits;
988    typedef typename __make_tree_node_types<value_type,
989        typename __alloc_traits::void_pointer>::type
990                                                    _NodeTypes;
991    typedef typename _NodeTypes::key_type           key_type;
992public:
993    typedef typename _NodeTypes::__node_value_type      __node_value_type;
994    typedef typename _NodeTypes::__container_value_type __container_value_type;
995
996    typedef typename __alloc_traits::pointer         pointer;
997    typedef typename __alloc_traits::const_pointer   const_pointer;
998    typedef typename __alloc_traits::size_type       size_type;
999    typedef typename __alloc_traits::difference_type difference_type;
1000
1001public:
1002    typedef typename _NodeTypes::__void_pointer        __void_pointer;
1003
1004    typedef typename _NodeTypes::__node_type           __node;
1005    typedef typename _NodeTypes::__node_pointer        __node_pointer;
1006
1007    typedef typename _NodeTypes::__node_base_type      __node_base;
1008    typedef typename _NodeTypes::__node_base_pointer   __node_base_pointer;
1009
1010    typedef typename _NodeTypes::__end_node_type       __end_node_t;
1011    typedef typename _NodeTypes::__end_node_pointer    __end_node_ptr;
1012
1013    typedef typename _NodeTypes::__parent_pointer      __parent_pointer;
1014    typedef typename _NodeTypes::__iter_pointer        __iter_pointer;
1015
1016    typedef typename __rebind_alloc_helper<__alloc_traits, __node>::type __node_allocator;
1017    typedef allocator_traits<__node_allocator>         __node_traits;
1018
1019private:
1020    // check for sane allocator pointer rebinding semantics. Rebinding the
1021    // allocator for a new pointer type should be exactly the same as rebinding
1022    // the pointer using 'pointer_traits'.
1023    static_assert((is_same<__node_pointer, typename __node_traits::pointer>::value),
1024                  "Allocator does not rebind pointers in a sane manner.");
1025    typedef typename __rebind_alloc_helper<__node_traits, __node_base>::type
1026        __node_base_allocator;
1027    typedef allocator_traits<__node_base_allocator> __node_base_traits;
1028    static_assert((is_same<__node_base_pointer, typename __node_base_traits::pointer>::value),
1029                 "Allocator does not rebind pointers in a sane manner.");
1030
1031private:
1032    __iter_pointer                                     __begin_node_;
1033    __compressed_pair<__end_node_t, __node_allocator>  __pair1_;
1034    __compressed_pair<size_type, value_compare>        __pair3_;
1035
1036public:
1037    _LIBCPP_INLINE_VISIBILITY
1038    __iter_pointer __end_node() _NOEXCEPT
1039    {
1040        return static_cast<__iter_pointer>(
1041                pointer_traits<__end_node_ptr>::pointer_to(__pair1_.first())
1042        );
1043    }
1044    _LIBCPP_INLINE_VISIBILITY
1045    __iter_pointer __end_node() const _NOEXCEPT
1046    {
1047        return static_cast<__iter_pointer>(
1048            pointer_traits<__end_node_ptr>::pointer_to(
1049                const_cast<__end_node_t&>(__pair1_.first())
1050            )
1051        );
1052    }
1053    _LIBCPP_INLINE_VISIBILITY
1054          __node_allocator& __node_alloc() _NOEXCEPT {return __pair1_.second();}
1055private:
1056    _LIBCPP_INLINE_VISIBILITY
1057    const __node_allocator& __node_alloc() const _NOEXCEPT
1058        {return __pair1_.second();}
1059    _LIBCPP_INLINE_VISIBILITY
1060          __iter_pointer& __begin_node() _NOEXCEPT {return __begin_node_;}
1061    _LIBCPP_INLINE_VISIBILITY
1062    const __iter_pointer& __begin_node() const _NOEXCEPT {return __begin_node_;}
1063public:
1064    _LIBCPP_INLINE_VISIBILITY
1065    allocator_type __alloc() const _NOEXCEPT
1066        {return allocator_type(__node_alloc());}
1067private:
1068    _LIBCPP_INLINE_VISIBILITY
1069          size_type& size() _NOEXCEPT {return __pair3_.first();}
1070public:
1071    _LIBCPP_INLINE_VISIBILITY
1072    const size_type& size() const _NOEXCEPT {return __pair3_.first();}
1073    _LIBCPP_INLINE_VISIBILITY
1074          value_compare& value_comp() _NOEXCEPT {return __pair3_.second();}
1075    _LIBCPP_INLINE_VISIBILITY
1076    const value_compare& value_comp() const _NOEXCEPT
1077        {return __pair3_.second();}
1078public:
1079
1080    _LIBCPP_INLINE_VISIBILITY
1081    __node_pointer __root() const _NOEXCEPT
1082        {return static_cast<__node_pointer>(__end_node()->__left_);}
1083
1084    __node_base_pointer* __root_ptr() const _NOEXCEPT {
1085        return _VSTD::addressof(__end_node()->__left_);
1086    }
1087
1088    typedef __tree_iterator<value_type, __node_pointer, difference_type>             iterator;
1089    typedef __tree_const_iterator<value_type, __node_pointer, difference_type> const_iterator;
1090
1091    explicit __tree(const value_compare& __comp)
1092        _NOEXCEPT_(
1093            is_nothrow_default_constructible<__node_allocator>::value &&
1094            is_nothrow_copy_constructible<value_compare>::value);
1095    explicit __tree(const allocator_type& __a);
1096    __tree(const value_compare& __comp, const allocator_type& __a);
1097    __tree(const __tree& __t);
1098    __tree& operator=(const __tree& __t);
1099    template <class _InputIterator>
1100        void __assign_unique(_InputIterator __first, _InputIterator __last);
1101    template <class _InputIterator>
1102        void __assign_multi(_InputIterator __first, _InputIterator __last);
1103#ifndef _LIBCPP_CXX03_LANG
1104    __tree(__tree&& __t)
1105        _NOEXCEPT_(
1106            is_nothrow_move_constructible<__node_allocator>::value &&
1107            is_nothrow_move_constructible<value_compare>::value);
1108    __tree(__tree&& __t, const allocator_type& __a);
1109    __tree& operator=(__tree&& __t)
1110        _NOEXCEPT_(
1111            __node_traits::propagate_on_container_move_assignment::value &&
1112            is_nothrow_move_assignable<value_compare>::value &&
1113            is_nothrow_move_assignable<__node_allocator>::value);
1114#endif // _LIBCPP_CXX03_LANG
1115
1116    ~__tree();
1117
1118    _LIBCPP_INLINE_VISIBILITY
1119          iterator begin()  _NOEXCEPT {return       iterator(__begin_node());}
1120    _LIBCPP_INLINE_VISIBILITY
1121    const_iterator begin() const _NOEXCEPT {return const_iterator(__begin_node());}
1122    _LIBCPP_INLINE_VISIBILITY
1123          iterator end() _NOEXCEPT {return       iterator(__end_node());}
1124    _LIBCPP_INLINE_VISIBILITY
1125    const_iterator end() const _NOEXCEPT {return const_iterator(__end_node());}
1126
1127    _LIBCPP_INLINE_VISIBILITY
1128    size_type max_size() const _NOEXCEPT
1129        {return std::min<size_type>(
1130                __node_traits::max_size(__node_alloc()),
1131                numeric_limits<difference_type >::max());}
1132
1133    void clear() _NOEXCEPT;
1134
1135    void swap(__tree& __t)
1136#if _LIBCPP_STD_VER <= 11
1137        _NOEXCEPT_(
1138            __is_nothrow_swappable<value_compare>::value
1139            && (!__node_traits::propagate_on_container_swap::value ||
1140                 __is_nothrow_swappable<__node_allocator>::value)
1141            );
1142#else
1143        _NOEXCEPT_(__is_nothrow_swappable<value_compare>::value);
1144#endif
1145
1146#ifndef _LIBCPP_CXX03_LANG
1147    template <class _Key, class ..._Args>
1148    pair<iterator, bool>
1149    __emplace_unique_key_args(_Key const&, _Args&&... __args);
1150    template <class _Key, class ..._Args>
1151    iterator
1152    __emplace_hint_unique_key_args(const_iterator, _Key const&, _Args&&...);
1153
1154    template <class... _Args>
1155    pair<iterator, bool> __emplace_unique_impl(_Args&&... __args);
1156
1157    template <class... _Args>
1158    iterator __emplace_hint_unique_impl(const_iterator __p, _Args&&... __args);
1159
1160    template <class... _Args>
1161    iterator __emplace_multi(_Args&&... __args);
1162
1163    template <class... _Args>
1164    iterator __emplace_hint_multi(const_iterator __p, _Args&&... __args);
1165
1166    template <class _Pp>
1167    _LIBCPP_INLINE_VISIBILITY
1168    pair<iterator, bool> __emplace_unique(_Pp&& __x) {
1169        return __emplace_unique_extract_key(_VSTD::forward<_Pp>(__x),
1170                                            __can_extract_key<_Pp, key_type>());
1171    }
1172
1173    template <class _First, class _Second>
1174    _LIBCPP_INLINE_VISIBILITY
1175    typename enable_if<
1176        __can_extract_map_key<_First, key_type, __container_value_type>::value,
1177        pair<iterator, bool>
1178    >::type __emplace_unique(_First&& __f, _Second&& __s) {
1179        return __emplace_unique_key_args(__f, _VSTD::forward<_First>(__f),
1180                                              _VSTD::forward<_Second>(__s));
1181    }
1182
1183    template <class... _Args>
1184    _LIBCPP_INLINE_VISIBILITY
1185    pair<iterator, bool> __emplace_unique(_Args&&... __args) {
1186        return __emplace_unique_impl(_VSTD::forward<_Args>(__args)...);
1187    }
1188
1189    template <class _Pp>
1190    _LIBCPP_INLINE_VISIBILITY
1191    pair<iterator, bool>
1192    __emplace_unique_extract_key(_Pp&& __x, __extract_key_fail_tag) {
1193      return __emplace_unique_impl(_VSTD::forward<_Pp>(__x));
1194    }
1195
1196    template <class _Pp>
1197    _LIBCPP_INLINE_VISIBILITY
1198    pair<iterator, bool>
1199    __emplace_unique_extract_key(_Pp&& __x, __extract_key_self_tag) {
1200      return __emplace_unique_key_args(__x, _VSTD::forward<_Pp>(__x));
1201    }
1202
1203    template <class _Pp>
1204    _LIBCPP_INLINE_VISIBILITY
1205    pair<iterator, bool>
1206    __emplace_unique_extract_key(_Pp&& __x, __extract_key_first_tag) {
1207      return __emplace_unique_key_args(__x.first, _VSTD::forward<_Pp>(__x));
1208    }
1209
1210    template <class _Pp>
1211    _LIBCPP_INLINE_VISIBILITY
1212    iterator __emplace_hint_unique(const_iterator __p, _Pp&& __x) {
1213        return __emplace_hint_unique_extract_key(__p, _VSTD::forward<_Pp>(__x),
1214                                            __can_extract_key<_Pp, key_type>());
1215    }
1216
1217    template <class _First, class _Second>
1218    _LIBCPP_INLINE_VISIBILITY
1219    typename enable_if<
1220        __can_extract_map_key<_First, key_type, __container_value_type>::value,
1221        iterator
1222    >::type __emplace_hint_unique(const_iterator __p, _First&& __f, _Second&& __s) {
1223        return __emplace_hint_unique_key_args(__p, __f,
1224                                              _VSTD::forward<_First>(__f),
1225                                              _VSTD::forward<_Second>(__s));
1226    }
1227
1228    template <class... _Args>
1229    _LIBCPP_INLINE_VISIBILITY
1230    iterator __emplace_hint_unique(const_iterator __p, _Args&&... __args) {
1231        return __emplace_hint_unique_impl(__p, _VSTD::forward<_Args>(__args)...);
1232    }
1233
1234    template <class _Pp>
1235    _LIBCPP_INLINE_VISIBILITY
1236    iterator
1237    __emplace_hint_unique_extract_key(const_iterator __p, _Pp&& __x, __extract_key_fail_tag) {
1238      return __emplace_hint_unique_impl(__p, _VSTD::forward<_Pp>(__x));
1239    }
1240
1241    template <class _Pp>
1242    _LIBCPP_INLINE_VISIBILITY
1243    iterator
1244    __emplace_hint_unique_extract_key(const_iterator __p, _Pp&& __x, __extract_key_self_tag) {
1245      return __emplace_hint_unique_key_args(__p, __x, _VSTD::forward<_Pp>(__x));
1246    }
1247
1248    template <class _Pp>
1249    _LIBCPP_INLINE_VISIBILITY
1250    iterator
1251    __emplace_hint_unique_extract_key(const_iterator __p, _Pp&& __x, __extract_key_first_tag) {
1252      return __emplace_hint_unique_key_args(__p, __x.first, _VSTD::forward<_Pp>(__x));
1253    }
1254
1255#else
1256    template <class _Key, class _Args>
1257    _LIBCPP_INLINE_VISIBILITY
1258    pair<iterator, bool> __emplace_unique_key_args(_Key const&, _Args& __args);
1259    template <class _Key, class _Args>
1260    _LIBCPP_INLINE_VISIBILITY
1261    iterator __emplace_hint_unique_key_args(const_iterator, _Key const&, _Args&);
1262#endif
1263
1264    _LIBCPP_INLINE_VISIBILITY
1265    pair<iterator, bool> __insert_unique(const __container_value_type& __v) {
1266        return __emplace_unique_key_args(_NodeTypes::__get_key(__v), __v);
1267    }
1268
1269    _LIBCPP_INLINE_VISIBILITY
1270    iterator __insert_unique(const_iterator __p, const __container_value_type& __v) {
1271        return __emplace_hint_unique_key_args(__p, _NodeTypes::__get_key(__v), __v);
1272    }
1273
1274#ifdef _LIBCPP_CXX03_LANG
1275    _LIBCPP_INLINE_VISIBILITY
1276    iterator __insert_multi(const __container_value_type& __v);
1277    _LIBCPP_INLINE_VISIBILITY
1278    iterator __insert_multi(const_iterator __p, const __container_value_type& __v);
1279#else
1280    _LIBCPP_INLINE_VISIBILITY
1281    pair<iterator, bool> __insert_unique(__container_value_type&& __v) {
1282        return __emplace_unique_key_args(_NodeTypes::__get_key(__v), _VSTD::move(__v));
1283    }
1284
1285    _LIBCPP_INLINE_VISIBILITY
1286    iterator __insert_unique(const_iterator __p, __container_value_type&& __v) {
1287        return __emplace_hint_unique_key_args(__p, _NodeTypes::__get_key(__v), _VSTD::move(__v));
1288    }
1289
1290    template <class _Vp, class = typename enable_if<
1291            !is_same<typename __unconstref<_Vp>::type,
1292                     __container_value_type
1293            >::value
1294        >::type>
1295    _LIBCPP_INLINE_VISIBILITY
1296    pair<iterator, bool> __insert_unique(_Vp&& __v) {
1297        return __emplace_unique(_VSTD::forward<_Vp>(__v));
1298    }
1299
1300    template <class _Vp, class = typename enable_if<
1301            !is_same<typename __unconstref<_Vp>::type,
1302                     __container_value_type
1303            >::value
1304        >::type>
1305    _LIBCPP_INLINE_VISIBILITY
1306    iterator __insert_unique(const_iterator __p, _Vp&& __v) {
1307        return __emplace_hint_unique(__p, _VSTD::forward<_Vp>(__v));
1308    }
1309
1310    _LIBCPP_INLINE_VISIBILITY
1311    iterator __insert_multi(__container_value_type&& __v) {
1312        return __emplace_multi(_VSTD::move(__v));
1313    }
1314
1315    _LIBCPP_INLINE_VISIBILITY
1316    iterator __insert_multi(const_iterator __p, __container_value_type&& __v) {
1317        return __emplace_hint_multi(__p, _VSTD::move(__v));
1318    }
1319
1320    template <class _Vp>
1321    _LIBCPP_INLINE_VISIBILITY
1322    iterator __insert_multi(_Vp&& __v) {
1323        return __emplace_multi(_VSTD::forward<_Vp>(__v));
1324    }
1325
1326    template <class _Vp>
1327    _LIBCPP_INLINE_VISIBILITY
1328    iterator __insert_multi(const_iterator __p, _Vp&& __v) {
1329        return __emplace_hint_multi(__p, _VSTD::forward<_Vp>(__v));
1330    }
1331
1332#endif // !_LIBCPP_CXX03_LANG
1333
1334    _LIBCPP_INLINE_VISIBILITY
1335    pair<iterator, bool> __node_insert_unique(__node_pointer __nd);
1336    _LIBCPP_INLINE_VISIBILITY
1337    iterator             __node_insert_unique(const_iterator __p,
1338                                              __node_pointer __nd);
1339
1340    _LIBCPP_INLINE_VISIBILITY
1341    iterator __node_insert_multi(__node_pointer __nd);
1342    _LIBCPP_INLINE_VISIBILITY
1343    iterator __node_insert_multi(const_iterator __p, __node_pointer __nd);
1344
1345
1346    _LIBCPP_INLINE_VISIBILITY iterator
1347    __remove_node_pointer(__node_pointer) _NOEXCEPT;
1348
1349#if _LIBCPP_STD_VER > 14
1350    template <class _NodeHandle, class _InsertReturnType>
1351    _LIBCPP_INLINE_VISIBILITY
1352    _InsertReturnType __node_handle_insert_unique(_NodeHandle&&);
1353    template <class _NodeHandle>
1354    _LIBCPP_INLINE_VISIBILITY
1355    iterator __node_handle_insert_unique(const_iterator, _NodeHandle&&);
1356    template <class _Tree>
1357    _LIBCPP_INLINE_VISIBILITY
1358    void __node_handle_merge_unique(_Tree& __source);
1359
1360    template <class _NodeHandle>
1361    _LIBCPP_INLINE_VISIBILITY
1362    iterator __node_handle_insert_multi(_NodeHandle&&);
1363    template <class _NodeHandle>
1364    _LIBCPP_INLINE_VISIBILITY
1365    iterator __node_handle_insert_multi(const_iterator, _NodeHandle&&);
1366    template <class _Tree>
1367    _LIBCPP_INLINE_VISIBILITY
1368    void __node_handle_merge_multi(_Tree& __source);
1369
1370
1371    template <class _NodeHandle>
1372    _LIBCPP_INLINE_VISIBILITY
1373    _NodeHandle __node_handle_extract(key_type const&);
1374    template <class _NodeHandle>
1375    _LIBCPP_INLINE_VISIBILITY
1376    _NodeHandle __node_handle_extract(const_iterator);
1377#endif
1378
1379    iterator erase(const_iterator __p);
1380    iterator erase(const_iterator __f, const_iterator __l);
1381    template <class _Key>
1382        size_type __erase_unique(const _Key& __k);
1383    template <class _Key>
1384        size_type __erase_multi(const _Key& __k);
1385
1386    void __insert_node_at(__parent_pointer     __parent,
1387                          __node_base_pointer& __child,
1388                          __node_base_pointer __new_node) _NOEXCEPT;
1389
1390    template <class _Key>
1391        iterator find(const _Key& __v);
1392    template <class _Key>
1393        const_iterator find(const _Key& __v) const;
1394
1395    template <class _Key>
1396        size_type __count_unique(const _Key& __k) const;
1397    template <class _Key>
1398        size_type __count_multi(const _Key& __k) const;
1399
1400    template <class _Key>
1401        _LIBCPP_INLINE_VISIBILITY
1402        iterator lower_bound(const _Key& __v)
1403            {return __lower_bound(__v, __root(), __end_node());}
1404    template <class _Key>
1405        iterator __lower_bound(const _Key& __v,
1406                               __node_pointer __root,
1407                               __iter_pointer __result);
1408    template <class _Key>
1409        _LIBCPP_INLINE_VISIBILITY
1410        const_iterator lower_bound(const _Key& __v) const
1411            {return __lower_bound(__v, __root(), __end_node());}
1412    template <class _Key>
1413        const_iterator __lower_bound(const _Key& __v,
1414                                     __node_pointer __root,
1415                                     __iter_pointer __result) const;
1416    template <class _Key>
1417        _LIBCPP_INLINE_VISIBILITY
1418        iterator upper_bound(const _Key& __v)
1419            {return __upper_bound(__v, __root(), __end_node());}
1420    template <class _Key>
1421        iterator __upper_bound(const _Key& __v,
1422                               __node_pointer __root,
1423                               __iter_pointer __result);
1424    template <class _Key>
1425        _LIBCPP_INLINE_VISIBILITY
1426        const_iterator upper_bound(const _Key& __v) const
1427            {return __upper_bound(__v, __root(), __end_node());}
1428    template <class _Key>
1429        const_iterator __upper_bound(const _Key& __v,
1430                                     __node_pointer __root,
1431                                     __iter_pointer __result) const;
1432    template <class _Key>
1433        pair<iterator, iterator>
1434        __equal_range_unique(const _Key& __k);
1435    template <class _Key>
1436        pair<const_iterator, const_iterator>
1437        __equal_range_unique(const _Key& __k) const;
1438
1439    template <class _Key>
1440        pair<iterator, iterator>
1441        __equal_range_multi(const _Key& __k);
1442    template <class _Key>
1443        pair<const_iterator, const_iterator>
1444        __equal_range_multi(const _Key& __k) const;
1445
1446    typedef __tree_node_destructor<__node_allocator> _Dp;
1447    typedef unique_ptr<__node, _Dp> __node_holder;
1448
1449    __node_holder remove(const_iterator __p) _NOEXCEPT;
1450private:
1451    __node_base_pointer&
1452        __find_leaf_low(__parent_pointer& __parent, const key_type& __v);
1453    __node_base_pointer&
1454        __find_leaf_high(__parent_pointer& __parent, const key_type& __v);
1455    __node_base_pointer&
1456        __find_leaf(const_iterator __hint,
1457                    __parent_pointer& __parent, const key_type& __v);
1458    // FIXME: Make this function const qualified. Unfortunetly doing so
1459    // breaks existing code which uses non-const callable comparators.
1460    template <class _Key>
1461    __node_base_pointer&
1462        __find_equal(__parent_pointer& __parent, const _Key& __v);
1463    template <class _Key>
1464    _LIBCPP_INLINE_VISIBILITY __node_base_pointer&
1465    __find_equal(__parent_pointer& __parent, const _Key& __v) const {
1466      return const_cast<__tree*>(this)->__find_equal(__parent, __v);
1467    }
1468    template <class _Key>
1469    __node_base_pointer&
1470        __find_equal(const_iterator __hint, __parent_pointer& __parent,
1471                     __node_base_pointer& __dummy,
1472                     const _Key& __v);
1473
1474#ifndef _LIBCPP_CXX03_LANG
1475    template <class ..._Args>
1476    __node_holder __construct_node(_Args&& ...__args);
1477#else
1478    __node_holder __construct_node(const __container_value_type& __v);
1479#endif
1480
1481    void destroy(__node_pointer __nd) _NOEXCEPT;
1482
1483    _LIBCPP_INLINE_VISIBILITY
1484    void __copy_assign_alloc(const __tree& __t)
1485        {__copy_assign_alloc(__t, integral_constant<bool,
1486             __node_traits::propagate_on_container_copy_assignment::value>());}
1487
1488    _LIBCPP_INLINE_VISIBILITY
1489    void __copy_assign_alloc(const __tree& __t, true_type)
1490        {
1491        if (__node_alloc() != __t.__node_alloc())
1492            clear();
1493        __node_alloc() = __t.__node_alloc();
1494        }
1495    _LIBCPP_INLINE_VISIBILITY
1496    void __copy_assign_alloc(const __tree&, false_type) {}
1497
1498    void __move_assign(__tree& __t, false_type);
1499    void __move_assign(__tree& __t, true_type)
1500        _NOEXCEPT_(is_nothrow_move_assignable<value_compare>::value &&
1501                   is_nothrow_move_assignable<__node_allocator>::value);
1502
1503    _LIBCPP_INLINE_VISIBILITY
1504    void __move_assign_alloc(__tree& __t)
1505        _NOEXCEPT_(
1506            !__node_traits::propagate_on_container_move_assignment::value ||
1507            is_nothrow_move_assignable<__node_allocator>::value)
1508        {__move_assign_alloc(__t, integral_constant<bool,
1509             __node_traits::propagate_on_container_move_assignment::value>());}
1510
1511    _LIBCPP_INLINE_VISIBILITY
1512    void __move_assign_alloc(__tree& __t, true_type)
1513        _NOEXCEPT_(is_nothrow_move_assignable<__node_allocator>::value)
1514        {__node_alloc() = _VSTD::move(__t.__node_alloc());}
1515    _LIBCPP_INLINE_VISIBILITY
1516    void __move_assign_alloc(__tree&, false_type) _NOEXCEPT {}
1517
1518    __node_pointer __detach();
1519    static __node_pointer __detach(__node_pointer);
1520
1521    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS map;
1522    template <class, class, class, class> friend class _LIBCPP_TEMPLATE_VIS multimap;
1523};
1524
1525template <class _Tp, class _Compare, class _Allocator>
1526__tree<_Tp, _Compare, _Allocator>::__tree(const value_compare& __comp)
1527        _NOEXCEPT_(
1528            is_nothrow_default_constructible<__node_allocator>::value &&
1529            is_nothrow_copy_constructible<value_compare>::value)
1530    : __pair3_(0, __comp)
1531{
1532    __begin_node() = __end_node();
1533}
1534
1535template <class _Tp, class _Compare, class _Allocator>
1536__tree<_Tp, _Compare, _Allocator>::__tree(const allocator_type& __a)
1537    : __begin_node_(__iter_pointer()),
1538      __pair1_(__second_tag(), __node_allocator(__a)),
1539      __pair3_(0)
1540{
1541    __begin_node() = __end_node();
1542}
1543
1544template <class _Tp, class _Compare, class _Allocator>
1545__tree<_Tp, _Compare, _Allocator>::__tree(const value_compare& __comp,
1546                                           const allocator_type& __a)
1547    : __begin_node_(__iter_pointer()),
1548      __pair1_(__second_tag(), __node_allocator(__a)),
1549      __pair3_(0, __comp)
1550{
1551    __begin_node() = __end_node();
1552}
1553
1554// Precondition:  size() != 0
1555template <class _Tp, class _Compare, class _Allocator>
1556typename __tree<_Tp, _Compare, _Allocator>::__node_pointer
1557__tree<_Tp, _Compare, _Allocator>::__detach()
1558{
1559    __node_pointer __cache = static_cast<__node_pointer>(__begin_node());
1560    __begin_node() = __end_node();
1561    __end_node()->__left_->__parent_ = nullptr;
1562    __end_node()->__left_ = nullptr;
1563    size() = 0;
1564    // __cache->__left_ == nullptr
1565    if (__cache->__right_ != nullptr)
1566        __cache = static_cast<__node_pointer>(__cache->__right_);
1567    // __cache->__left_ == nullptr
1568    // __cache->__right_ == nullptr
1569    return __cache;
1570}
1571
1572// Precondition:  __cache != nullptr
1573//    __cache->left_ == nullptr
1574//    __cache->right_ == nullptr
1575//    This is no longer a red-black tree
1576template <class _Tp, class _Compare, class _Allocator>
1577typename __tree<_Tp, _Compare, _Allocator>::__node_pointer
1578__tree<_Tp, _Compare, _Allocator>::__detach(__node_pointer __cache)
1579{
1580    if (__cache->__parent_ == nullptr)
1581        return nullptr;
1582    if (__tree_is_left_child(static_cast<__node_base_pointer>(__cache)))
1583    {
1584        __cache->__parent_->__left_ = nullptr;
1585        __cache = static_cast<__node_pointer>(__cache->__parent_);
1586        if (__cache->__right_ == nullptr)
1587            return __cache;
1588        return static_cast<__node_pointer>(__tree_leaf(__cache->__right_));
1589    }
1590    // __cache is right child
1591    __cache->__parent_unsafe()->__right_ = nullptr;
1592    __cache = static_cast<__node_pointer>(__cache->__parent_);
1593    if (__cache->__left_ == nullptr)
1594        return __cache;
1595    return static_cast<__node_pointer>(__tree_leaf(__cache->__left_));
1596}
1597
1598template <class _Tp, class _Compare, class _Allocator>
1599__tree<_Tp, _Compare, _Allocator>&
1600__tree<_Tp, _Compare, _Allocator>::operator=(const __tree& __t)
1601{
1602    if (this != &__t)
1603    {
1604        value_comp() = __t.value_comp();
1605        __copy_assign_alloc(__t);
1606        __assign_multi(__t.begin(), __t.end());
1607    }
1608    return *this;
1609}
1610
1611template <class _Tp, class _Compare, class _Allocator>
1612template <class _InputIterator>
1613void
1614__tree<_Tp, _Compare, _Allocator>::__assign_unique(_InputIterator __first, _InputIterator __last)
1615{
1616    typedef iterator_traits<_InputIterator> _ITraits;
1617    typedef typename _ITraits::value_type _ItValueType;
1618    static_assert((is_same<_ItValueType, __container_value_type>::value),
1619                  "__assign_unique may only be called with the containers value type");
1620
1621    if (size() != 0)
1622    {
1623        __node_pointer __cache = __detach();
1624#ifndef _LIBCPP_NO_EXCEPTIONS
1625        try
1626        {
1627#endif  // _LIBCPP_NO_EXCEPTIONS
1628            for (; __cache != nullptr && __first != __last; ++__first)
1629            {
1630                __cache->__value_ = *__first;
1631                __node_pointer __next = __detach(__cache);
1632                __node_insert_unique(__cache);
1633                __cache = __next;
1634            }
1635#ifndef _LIBCPP_NO_EXCEPTIONS
1636        }
1637        catch (...)
1638        {
1639            while (__cache->__parent_ != nullptr)
1640                __cache = static_cast<__node_pointer>(__cache->__parent_);
1641            destroy(__cache);
1642            throw;
1643        }
1644#endif  // _LIBCPP_NO_EXCEPTIONS
1645        if (__cache != nullptr)
1646        {
1647            while (__cache->__parent_ != nullptr)
1648                __cache = static_cast<__node_pointer>(__cache->__parent_);
1649            destroy(__cache);
1650        }
1651    }
1652    for (; __first != __last; ++__first)
1653        __insert_unique(*__first);
1654}
1655
1656template <class _Tp, class _Compare, class _Allocator>
1657template <class _InputIterator>
1658void
1659__tree<_Tp, _Compare, _Allocator>::__assign_multi(_InputIterator __first, _InputIterator __last)
1660{
1661    typedef iterator_traits<_InputIterator> _ITraits;
1662    typedef typename _ITraits::value_type _ItValueType;
1663    static_assert((is_same<_ItValueType, __container_value_type>::value ||
1664                  is_same<_ItValueType, __node_value_type>::value),
1665                  "__assign_multi may only be called with the containers value type"
1666                  " or the nodes value type");
1667    if (size() != 0)
1668    {
1669        __node_pointer __cache = __detach();
1670#ifndef _LIBCPP_NO_EXCEPTIONS
1671        try
1672        {
1673#endif  // _LIBCPP_NO_EXCEPTIONS
1674            for (; __cache != nullptr && __first != __last; ++__first)
1675            {
1676                __cache->__value_ = *__first;
1677                __node_pointer __next = __detach(__cache);
1678                __node_insert_multi(__cache);
1679                __cache = __next;
1680            }
1681#ifndef _LIBCPP_NO_EXCEPTIONS
1682        }
1683        catch (...)
1684        {
1685            while (__cache->__parent_ != nullptr)
1686                __cache = static_cast<__node_pointer>(__cache->__parent_);
1687            destroy(__cache);
1688            throw;
1689        }
1690#endif  // _LIBCPP_NO_EXCEPTIONS
1691        if (__cache != nullptr)
1692        {
1693            while (__cache->__parent_ != nullptr)
1694                __cache = static_cast<__node_pointer>(__cache->__parent_);
1695            destroy(__cache);
1696        }
1697    }
1698    for (; __first != __last; ++__first)
1699        __insert_multi(_NodeTypes::__get_value(*__first));
1700}
1701
1702template <class _Tp, class _Compare, class _Allocator>
1703__tree<_Tp, _Compare, _Allocator>::__tree(const __tree& __t)
1704    : __begin_node_(__iter_pointer()),
1705      __pair1_(__second_tag(), __node_traits::select_on_container_copy_construction(__t.__node_alloc())),
1706      __pair3_(0, __t.value_comp())
1707{
1708    __begin_node() = __end_node();
1709}
1710
1711#ifndef _LIBCPP_CXX03_LANG
1712
1713template <class _Tp, class _Compare, class _Allocator>
1714__tree<_Tp, _Compare, _Allocator>::__tree(__tree&& __t)
1715    _NOEXCEPT_(
1716        is_nothrow_move_constructible<__node_allocator>::value &&
1717        is_nothrow_move_constructible<value_compare>::value)
1718    : __begin_node_(_VSTD::move(__t.__begin_node_)),
1719      __pair1_(_VSTD::move(__t.__pair1_)),
1720      __pair3_(_VSTD::move(__t.__pair3_))
1721{
1722    if (size() == 0)
1723        __begin_node() = __end_node();
1724    else
1725    {
1726        __end_node()->__left_->__parent_ = static_cast<__parent_pointer>(__end_node());
1727        __t.__begin_node() = __t.__end_node();
1728        __t.__end_node()->__left_ = nullptr;
1729        __t.size() = 0;
1730    }
1731}
1732
1733template <class _Tp, class _Compare, class _Allocator>
1734__tree<_Tp, _Compare, _Allocator>::__tree(__tree&& __t, const allocator_type& __a)
1735    : __pair1_(__second_tag(), __node_allocator(__a)),
1736      __pair3_(0, _VSTD::move(__t.value_comp()))
1737{
1738    if (__a == __t.__alloc())
1739    {
1740        if (__t.size() == 0)
1741            __begin_node() = __end_node();
1742        else
1743        {
1744            __begin_node() = __t.__begin_node();
1745            __end_node()->__left_ = __t.__end_node()->__left_;
1746            __end_node()->__left_->__parent_ = static_cast<__parent_pointer>(__end_node());
1747            size() = __t.size();
1748            __t.__begin_node() = __t.__end_node();
1749            __t.__end_node()->__left_ = nullptr;
1750            __t.size() = 0;
1751        }
1752    }
1753    else
1754    {
1755        __begin_node() = __end_node();
1756    }
1757}
1758
1759template <class _Tp, class _Compare, class _Allocator>
1760void
1761__tree<_Tp, _Compare, _Allocator>::__move_assign(__tree& __t, true_type)
1762    _NOEXCEPT_(is_nothrow_move_assignable<value_compare>::value &&
1763               is_nothrow_move_assignable<__node_allocator>::value)
1764{
1765    destroy(static_cast<__node_pointer>(__end_node()->__left_));
1766    __begin_node_ = __t.__begin_node_;
1767    __pair1_.first() = __t.__pair1_.first();
1768    __move_assign_alloc(__t);
1769    __pair3_ = _VSTD::move(__t.__pair3_);
1770    if (size() == 0)
1771        __begin_node() = __end_node();
1772    else
1773    {
1774        __end_node()->__left_->__parent_ = static_cast<__parent_pointer>(__end_node());
1775        __t.__begin_node() = __t.__end_node();
1776        __t.__end_node()->__left_ = nullptr;
1777        __t.size() = 0;
1778    }
1779}
1780
1781template <class _Tp, class _Compare, class _Allocator>
1782void
1783__tree<_Tp, _Compare, _Allocator>::__move_assign(__tree& __t, false_type)
1784{
1785    if (__node_alloc() == __t.__node_alloc())
1786        __move_assign(__t, true_type());
1787    else
1788    {
1789        value_comp() = _VSTD::move(__t.value_comp());
1790        const_iterator __e = end();
1791        if (size() != 0)
1792        {
1793            __node_pointer __cache = __detach();
1794#ifndef _LIBCPP_NO_EXCEPTIONS
1795            try
1796            {
1797#endif  // _LIBCPP_NO_EXCEPTIONS
1798                while (__cache != nullptr && __t.size() != 0)
1799                {
1800                    __cache->__value_ = _VSTD::move(__t.remove(__t.begin())->__value_);
1801                    __node_pointer __next = __detach(__cache);
1802                    __node_insert_multi(__cache);
1803                    __cache = __next;
1804                }
1805#ifndef _LIBCPP_NO_EXCEPTIONS
1806            }
1807            catch (...)
1808            {
1809                while (__cache->__parent_ != nullptr)
1810                    __cache = static_cast<__node_pointer>(__cache->__parent_);
1811                destroy(__cache);
1812                throw;
1813            }
1814#endif  // _LIBCPP_NO_EXCEPTIONS
1815            if (__cache != nullptr)
1816            {
1817                while (__cache->__parent_ != nullptr)
1818                    __cache = static_cast<__node_pointer>(__cache->__parent_);
1819                destroy(__cache);
1820            }
1821        }
1822        while (__t.size() != 0)
1823            __insert_multi(__e, _NodeTypes::__move(__t.remove(__t.begin())->__value_));
1824    }
1825}
1826
1827template <class _Tp, class _Compare, class _Allocator>
1828__tree<_Tp, _Compare, _Allocator>&
1829__tree<_Tp, _Compare, _Allocator>::operator=(__tree&& __t)
1830    _NOEXCEPT_(
1831        __node_traits::propagate_on_container_move_assignment::value &&
1832        is_nothrow_move_assignable<value_compare>::value &&
1833        is_nothrow_move_assignable<__node_allocator>::value)
1834
1835{
1836    __move_assign(__t, integral_constant<bool,
1837                  __node_traits::propagate_on_container_move_assignment::value>());
1838    return *this;
1839}
1840
1841#endif  // _LIBCPP_CXX03_LANG
1842
1843template <class _Tp, class _Compare, class _Allocator>
1844__tree<_Tp, _Compare, _Allocator>::~__tree()
1845{
1846    static_assert((is_copy_constructible<value_compare>::value),
1847                 "Comparator must be copy-constructible.");
1848  destroy(__root());
1849}
1850
1851template <class _Tp, class _Compare, class _Allocator>
1852void
1853__tree<_Tp, _Compare, _Allocator>::destroy(__node_pointer __nd) _NOEXCEPT
1854{
1855    if (__nd != nullptr)
1856    {
1857        destroy(static_cast<__node_pointer>(__nd->__left_));
1858        destroy(static_cast<__node_pointer>(__nd->__right_));
1859        __node_allocator& __na = __node_alloc();
1860        __node_traits::destroy(__na, _NodeTypes::__get_ptr(__nd->__value_));
1861        __node_traits::deallocate(__na, __nd, 1);
1862    }
1863}
1864
1865template <class _Tp, class _Compare, class _Allocator>
1866void
1867__tree<_Tp, _Compare, _Allocator>::swap(__tree& __t)
1868#if _LIBCPP_STD_VER <= 11
1869        _NOEXCEPT_(
1870            __is_nothrow_swappable<value_compare>::value
1871            && (!__node_traits::propagate_on_container_swap::value ||
1872                 __is_nothrow_swappable<__node_allocator>::value)
1873            )
1874#else
1875        _NOEXCEPT_(__is_nothrow_swappable<value_compare>::value)
1876#endif
1877{
1878    using _VSTD::swap;
1879    swap(__begin_node_, __t.__begin_node_);
1880    swap(__pair1_.first(), __t.__pair1_.first());
1881    __swap_allocator(__node_alloc(), __t.__node_alloc());
1882    __pair3_.swap(__t.__pair3_);
1883    if (size() == 0)
1884        __begin_node() = __end_node();
1885    else
1886        __end_node()->__left_->__parent_ = static_cast<__parent_pointer>(__end_node());
1887    if (__t.size() == 0)
1888        __t.__begin_node() = __t.__end_node();
1889    else
1890        __t.__end_node()->__left_->__parent_ = static_cast<__parent_pointer>(__t.__end_node());
1891}
1892
1893template <class _Tp, class _Compare, class _Allocator>
1894void
1895__tree<_Tp, _Compare, _Allocator>::clear() _NOEXCEPT
1896{
1897    destroy(__root());
1898    size() = 0;
1899    __begin_node() = __end_node();
1900    __end_node()->__left_ = nullptr;
1901}
1902
1903// Find lower_bound place to insert
1904// Set __parent to parent of null leaf
1905// Return reference to null leaf
1906template <class _Tp, class _Compare, class _Allocator>
1907typename __tree<_Tp, _Compare, _Allocator>::__node_base_pointer&
1908__tree<_Tp, _Compare, _Allocator>::__find_leaf_low(__parent_pointer& __parent,
1909                                                   const key_type& __v)
1910{
1911    __node_pointer __nd = __root();
1912    if (__nd != nullptr)
1913    {
1914        while (true)
1915        {
1916            if (value_comp()(__nd->__value_, __v))
1917            {
1918                if (__nd->__right_ != nullptr)
1919                    __nd = static_cast<__node_pointer>(__nd->__right_);
1920                else
1921                {
1922                    __parent = static_cast<__parent_pointer>(__nd);
1923                    return __nd->__right_;
1924                }
1925            }
1926            else
1927            {
1928                if (__nd->__left_ != nullptr)
1929                    __nd = static_cast<__node_pointer>(__nd->__left_);
1930                else
1931                {
1932                    __parent = static_cast<__parent_pointer>(__nd);
1933                    return __parent->__left_;
1934                }
1935            }
1936        }
1937    }
1938    __parent = static_cast<__parent_pointer>(__end_node());
1939    return __parent->__left_;
1940}
1941
1942// Find upper_bound place to insert
1943// Set __parent to parent of null leaf
1944// Return reference to null leaf
1945template <class _Tp, class _Compare, class _Allocator>
1946typename __tree<_Tp, _Compare, _Allocator>::__node_base_pointer&
1947__tree<_Tp, _Compare, _Allocator>::__find_leaf_high(__parent_pointer& __parent,
1948                                                    const key_type& __v)
1949{
1950    __node_pointer __nd = __root();
1951    if (__nd != nullptr)
1952    {
1953        while (true)
1954        {
1955            if (value_comp()(__v, __nd->__value_))
1956            {
1957                if (__nd->__left_ != nullptr)
1958                    __nd = static_cast<__node_pointer>(__nd->__left_);
1959                else
1960                {
1961                    __parent = static_cast<__parent_pointer>(__nd);
1962                    return __parent->__left_;
1963                }
1964            }
1965            else
1966            {
1967                if (__nd->__right_ != nullptr)
1968                    __nd = static_cast<__node_pointer>(__nd->__right_);
1969                else
1970                {
1971                    __parent = static_cast<__parent_pointer>(__nd);
1972                    return __nd->__right_;
1973                }
1974            }
1975        }
1976    }
1977    __parent = static_cast<__parent_pointer>(__end_node());
1978    return __parent->__left_;
1979}
1980
1981// Find leaf place to insert closest to __hint
1982// First check prior to __hint.
1983// Next check after __hint.
1984// Next do O(log N) search.
1985// Set __parent to parent of null leaf
1986// Return reference to null leaf
1987template <class _Tp, class _Compare, class _Allocator>
1988typename __tree<_Tp, _Compare, _Allocator>::__node_base_pointer&
1989__tree<_Tp, _Compare, _Allocator>::__find_leaf(const_iterator __hint,
1990                                               __parent_pointer& __parent,
1991                                               const key_type& __v)
1992{
1993    if (__hint == end() || !value_comp()(*__hint, __v))  // check before
1994    {
1995        // __v <= *__hint
1996        const_iterator __prior = __hint;
1997        if (__prior == begin() || !value_comp()(__v, *--__prior))
1998        {
1999            // *prev(__hint) <= __v <= *__hint
2000            if (__hint.__ptr_->__left_ == nullptr)
2001            {
2002                __parent = static_cast<__parent_pointer>(__hint.__ptr_);
2003                return __parent->__left_;
2004            }
2005            else
2006            {
2007                __parent = static_cast<__parent_pointer>(__prior.__ptr_);
2008                return static_cast<__node_base_pointer>(__prior.__ptr_)->__right_;
2009            }
2010        }
2011        // __v < *prev(__hint)
2012        return __find_leaf_high(__parent, __v);
2013    }
2014    // else __v > *__hint
2015    return __find_leaf_low(__parent, __v);
2016}
2017
2018// Find place to insert if __v doesn't exist
2019// Set __parent to parent of null leaf
2020// Return reference to null leaf
2021// If __v exists, set parent to node of __v and return reference to node of __v
2022template <class _Tp, class _Compare, class _Allocator>
2023template <class _Key>
2024typename __tree<_Tp, _Compare, _Allocator>::__node_base_pointer&
2025__tree<_Tp, _Compare, _Allocator>::__find_equal(__parent_pointer& __parent,
2026                                                const _Key& __v)
2027{
2028    __node_pointer __nd = __root();
2029    __node_base_pointer* __nd_ptr = __root_ptr();
2030    if (__nd != nullptr)
2031    {
2032        while (true)
2033        {
2034            if (value_comp()(__v, __nd->__value_))
2035            {
2036                if (__nd->__left_ != nullptr) {
2037                    __nd_ptr = _VSTD::addressof(__nd->__left_);
2038                    __nd = static_cast<__node_pointer>(__nd->__left_);
2039                } else {
2040                    __parent = static_cast<__parent_pointer>(__nd);
2041                    return __parent->__left_;
2042                }
2043            }
2044            else if (value_comp()(__nd->__value_, __v))
2045            {
2046                if (__nd->__right_ != nullptr) {
2047                    __nd_ptr = _VSTD::addressof(__nd->__right_);
2048                    __nd = static_cast<__node_pointer>(__nd->__right_);
2049                } else {
2050                    __parent = static_cast<__parent_pointer>(__nd);
2051                    return __nd->__right_;
2052                }
2053            }
2054            else
2055            {
2056                __parent = static_cast<__parent_pointer>(__nd);
2057                return *__nd_ptr;
2058            }
2059        }
2060    }
2061    __parent = static_cast<__parent_pointer>(__end_node());
2062    return __parent->__left_;
2063}
2064
2065// Find place to insert if __v doesn't exist
2066// First check prior to __hint.
2067// Next check after __hint.
2068// Next do O(log N) search.
2069// Set __parent to parent of null leaf
2070// Return reference to null leaf
2071// If __v exists, set parent to node of __v and return reference to node of __v
2072template <class _Tp, class _Compare, class _Allocator>
2073template <class _Key>
2074typename __tree<_Tp, _Compare, _Allocator>::__node_base_pointer&
2075__tree<_Tp, _Compare, _Allocator>::__find_equal(const_iterator __hint,
2076                                                __parent_pointer& __parent,
2077                                                __node_base_pointer& __dummy,
2078                                                const _Key& __v)
2079{
2080    if (__hint == end() || value_comp()(__v, *__hint))  // check before
2081    {
2082        // __v < *__hint
2083        const_iterator __prior = __hint;
2084        if (__prior == begin() || value_comp()(*--__prior, __v))
2085        {
2086            // *prev(__hint) < __v < *__hint
2087            if (__hint.__ptr_->__left_ == nullptr)
2088            {
2089                __parent = static_cast<__parent_pointer>(__hint.__ptr_);
2090                return __parent->__left_;
2091            }
2092            else
2093            {
2094                __parent = static_cast<__parent_pointer>(__prior.__ptr_);
2095                return static_cast<__node_base_pointer>(__prior.__ptr_)->__right_;
2096            }
2097        }
2098        // __v <= *prev(__hint)
2099        return __find_equal(__parent, __v);
2100    }
2101    else if (value_comp()(*__hint, __v))  // check after
2102    {
2103        // *__hint < __v
2104        const_iterator __next = _VSTD::next(__hint);
2105        if (__next == end() || value_comp()(__v, *__next))
2106        {
2107            // *__hint < __v < *_VSTD::next(__hint)
2108            if (__hint.__get_np()->__right_ == nullptr)
2109            {
2110                __parent = static_cast<__parent_pointer>(__hint.__ptr_);
2111                return static_cast<__node_base_pointer>(__hint.__ptr_)->__right_;
2112            }
2113            else
2114            {
2115                __parent = static_cast<__parent_pointer>(__next.__ptr_);
2116                return __parent->__left_;
2117            }
2118        }
2119        // *next(__hint) <= __v
2120        return __find_equal(__parent, __v);
2121    }
2122    // else __v == *__hint
2123    __parent = static_cast<__parent_pointer>(__hint.__ptr_);
2124    __dummy = static_cast<__node_base_pointer>(__hint.__ptr_);
2125    return __dummy;
2126}
2127
2128template <class _Tp, class _Compare, class _Allocator>
2129void __tree<_Tp, _Compare, _Allocator>::__insert_node_at(
2130    __parent_pointer __parent, __node_base_pointer& __child,
2131    __node_base_pointer __new_node) _NOEXCEPT
2132{
2133    __new_node->__left_   = nullptr;
2134    __new_node->__right_  = nullptr;
2135    __new_node->__parent_ = __parent;
2136    // __new_node->__is_black_ is initialized in __tree_balance_after_insert
2137    __child = __new_node;
2138    if (__begin_node()->__left_ != nullptr)
2139        __begin_node() = static_cast<__iter_pointer>(__begin_node()->__left_);
2140    __tree_balance_after_insert(__end_node()->__left_, __child);
2141    ++size();
2142}
2143
2144#ifndef _LIBCPP_CXX03_LANG
2145template <class _Tp, class _Compare, class _Allocator>
2146template <class _Key, class... _Args>
2147pair<typename __tree<_Tp, _Compare, _Allocator>::iterator, bool>
2148__tree<_Tp, _Compare, _Allocator>::__emplace_unique_key_args(_Key const& __k, _Args&&... __args)
2149#else
2150template <class _Tp, class _Compare, class _Allocator>
2151template <class _Key, class _Args>
2152pair<typename __tree<_Tp, _Compare, _Allocator>::iterator, bool>
2153__tree<_Tp, _Compare, _Allocator>::__emplace_unique_key_args(_Key const& __k, _Args& __args)
2154#endif
2155{
2156    __parent_pointer __parent;
2157    __node_base_pointer& __child = __find_equal(__parent, __k);
2158    __node_pointer __r = static_cast<__node_pointer>(__child);
2159    bool __inserted = false;
2160    if (__child == nullptr)
2161    {
2162#ifndef _LIBCPP_CXX03_LANG
2163        __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2164#else
2165        __node_holder __h = __construct_node(__args);
2166#endif
2167        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2168        __r = __h.release();
2169        __inserted = true;
2170    }
2171    return pair<iterator, bool>(iterator(__r), __inserted);
2172}
2173
2174
2175#ifndef _LIBCPP_CXX03_LANG
2176template <class _Tp, class _Compare, class _Allocator>
2177template <class _Key, class... _Args>
2178typename __tree<_Tp, _Compare, _Allocator>::iterator
2179__tree<_Tp, _Compare, _Allocator>::__emplace_hint_unique_key_args(
2180    const_iterator __p, _Key const& __k, _Args&&... __args)
2181#else
2182template <class _Tp, class _Compare, class _Allocator>
2183template <class _Key, class _Args>
2184typename __tree<_Tp, _Compare, _Allocator>::iterator
2185__tree<_Tp, _Compare, _Allocator>::__emplace_hint_unique_key_args(
2186    const_iterator __p, _Key const& __k, _Args& __args)
2187#endif
2188{
2189    __parent_pointer __parent;
2190    __node_base_pointer __dummy;
2191    __node_base_pointer& __child = __find_equal(__p, __parent, __dummy, __k);
2192    __node_pointer __r = static_cast<__node_pointer>(__child);
2193    if (__child == nullptr)
2194    {
2195#ifndef _LIBCPP_CXX03_LANG
2196        __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2197#else
2198        __node_holder __h = __construct_node(__args);
2199#endif
2200        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2201        __r = __h.release();
2202    }
2203    return iterator(__r);
2204}
2205
2206
2207#ifndef _LIBCPP_CXX03_LANG
2208
2209template <class _Tp, class _Compare, class _Allocator>
2210template <class ..._Args>
2211typename __tree<_Tp, _Compare, _Allocator>::__node_holder
2212__tree<_Tp, _Compare, _Allocator>::__construct_node(_Args&& ...__args)
2213{
2214    static_assert(!__is_tree_value_type<_Args...>::value,
2215                  "Cannot construct from __value_type");
2216    __node_allocator& __na = __node_alloc();
2217    __node_holder __h(__node_traits::allocate(__na, 1), _Dp(__na));
2218    __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), _VSTD::forward<_Args>(__args)...);
2219    __h.get_deleter().__value_constructed = true;
2220    return __h;
2221}
2222
2223
2224template <class _Tp, class _Compare, class _Allocator>
2225template <class... _Args>
2226pair<typename __tree<_Tp, _Compare, _Allocator>::iterator, bool>
2227__tree<_Tp, _Compare, _Allocator>::__emplace_unique_impl(_Args&&... __args)
2228{
2229    __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2230    __parent_pointer __parent;
2231    __node_base_pointer& __child = __find_equal(__parent, __h->__value_);
2232    __node_pointer __r = static_cast<__node_pointer>(__child);
2233    bool __inserted = false;
2234    if (__child == nullptr)
2235    {
2236        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2237        __r = __h.release();
2238        __inserted = true;
2239    }
2240    return pair<iterator, bool>(iterator(__r), __inserted);
2241}
2242
2243template <class _Tp, class _Compare, class _Allocator>
2244template <class... _Args>
2245typename __tree<_Tp, _Compare, _Allocator>::iterator
2246__tree<_Tp, _Compare, _Allocator>::__emplace_hint_unique_impl(const_iterator __p, _Args&&... __args)
2247{
2248    __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2249    __parent_pointer __parent;
2250    __node_base_pointer __dummy;
2251    __node_base_pointer& __child = __find_equal(__p, __parent, __dummy, __h->__value_);
2252    __node_pointer __r = static_cast<__node_pointer>(__child);
2253    if (__child == nullptr)
2254    {
2255        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2256        __r = __h.release();
2257    }
2258    return iterator(__r);
2259}
2260
2261template <class _Tp, class _Compare, class _Allocator>
2262template <class... _Args>
2263typename __tree<_Tp, _Compare, _Allocator>::iterator
2264__tree<_Tp, _Compare, _Allocator>::__emplace_multi(_Args&&... __args)
2265{
2266    __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2267    __parent_pointer __parent;
2268    __node_base_pointer& __child = __find_leaf_high(__parent, _NodeTypes::__get_key(__h->__value_));
2269    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2270    return iterator(static_cast<__node_pointer>(__h.release()));
2271}
2272
2273template <class _Tp, class _Compare, class _Allocator>
2274template <class... _Args>
2275typename __tree<_Tp, _Compare, _Allocator>::iterator
2276__tree<_Tp, _Compare, _Allocator>::__emplace_hint_multi(const_iterator __p,
2277                                                        _Args&&... __args)
2278{
2279    __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
2280    __parent_pointer __parent;
2281    __node_base_pointer& __child = __find_leaf(__p, __parent, _NodeTypes::__get_key(__h->__value_));
2282    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2283    return iterator(static_cast<__node_pointer>(__h.release()));
2284}
2285
2286
2287#else  // _LIBCPP_CXX03_LANG
2288
2289template <class _Tp, class _Compare, class _Allocator>
2290typename __tree<_Tp, _Compare, _Allocator>::__node_holder
2291__tree<_Tp, _Compare, _Allocator>::__construct_node(const __container_value_type& __v)
2292{
2293    __node_allocator& __na = __node_alloc();
2294    __node_holder __h(__node_traits::allocate(__na, 1), _Dp(__na));
2295    __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), __v);
2296    __h.get_deleter().__value_constructed = true;
2297    return _LIBCPP_EXPLICIT_MOVE(__h);  // explicitly moved for C++03
2298}
2299
2300#endif  // _LIBCPP_CXX03_LANG
2301
2302#ifdef _LIBCPP_CXX03_LANG
2303template <class _Tp, class _Compare, class _Allocator>
2304typename __tree<_Tp, _Compare, _Allocator>::iterator
2305__tree<_Tp, _Compare, _Allocator>::__insert_multi(const __container_value_type& __v)
2306{
2307    __parent_pointer __parent;
2308    __node_base_pointer& __child = __find_leaf_high(__parent, _NodeTypes::__get_key(__v));
2309    __node_holder __h = __construct_node(__v);
2310    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2311    return iterator(__h.release());
2312}
2313
2314template <class _Tp, class _Compare, class _Allocator>
2315typename __tree<_Tp, _Compare, _Allocator>::iterator
2316__tree<_Tp, _Compare, _Allocator>::__insert_multi(const_iterator __p, const __container_value_type& __v)
2317{
2318    __parent_pointer __parent;
2319    __node_base_pointer& __child = __find_leaf(__p, __parent, _NodeTypes::__get_key(__v));
2320    __node_holder __h = __construct_node(__v);
2321    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
2322    return iterator(__h.release());
2323}
2324#endif
2325
2326template <class _Tp, class _Compare, class _Allocator>
2327pair<typename __tree<_Tp, _Compare, _Allocator>::iterator, bool>
2328__tree<_Tp, _Compare, _Allocator>::__node_insert_unique(__node_pointer __nd)
2329{
2330    __parent_pointer __parent;
2331    __node_base_pointer& __child = __find_equal(__parent, __nd->__value_);
2332    __node_pointer __r = static_cast<__node_pointer>(__child);
2333    bool __inserted = false;
2334    if (__child == nullptr)
2335    {
2336        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__nd));
2337        __r = __nd;
2338        __inserted = true;
2339    }
2340    return pair<iterator, bool>(iterator(__r), __inserted);
2341}
2342
2343template <class _Tp, class _Compare, class _Allocator>
2344typename __tree<_Tp, _Compare, _Allocator>::iterator
2345__tree<_Tp, _Compare, _Allocator>::__node_insert_unique(const_iterator __p,
2346                                                        __node_pointer __nd)
2347{
2348    __parent_pointer __parent;
2349    __node_base_pointer __dummy;
2350    __node_base_pointer& __child = __find_equal(__p, __parent, __nd->__value_);
2351    __node_pointer __r = static_cast<__node_pointer>(__child);
2352    if (__child == nullptr)
2353    {
2354        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__nd));
2355        __r = __nd;
2356    }
2357    return iterator(__r);
2358}
2359
2360template <class _Tp, class _Compare, class _Allocator>
2361typename __tree<_Tp, _Compare, _Allocator>::iterator
2362__tree<_Tp, _Compare, _Allocator>::__node_insert_multi(__node_pointer __nd)
2363{
2364    __parent_pointer __parent;
2365    __node_base_pointer& __child = __find_leaf_high(__parent, _NodeTypes::__get_key(__nd->__value_));
2366    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__nd));
2367    return iterator(__nd);
2368}
2369
2370template <class _Tp, class _Compare, class _Allocator>
2371typename __tree<_Tp, _Compare, _Allocator>::iterator
2372__tree<_Tp, _Compare, _Allocator>::__node_insert_multi(const_iterator __p,
2373                                                       __node_pointer __nd)
2374{
2375    __parent_pointer __parent;
2376    __node_base_pointer& __child = __find_leaf(__p, __parent, _NodeTypes::__get_key(__nd->__value_));
2377    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__nd));
2378    return iterator(__nd);
2379}
2380
2381template <class _Tp, class _Compare, class _Allocator>
2382typename __tree<_Tp, _Compare, _Allocator>::iterator
2383__tree<_Tp, _Compare, _Allocator>::__remove_node_pointer(__node_pointer __ptr) _NOEXCEPT
2384{
2385    iterator __r(__ptr);
2386    ++__r;
2387    if (__begin_node() == __ptr)
2388        __begin_node() = __r.__ptr_;
2389    --size();
2390    __tree_remove(__end_node()->__left_,
2391                  static_cast<__node_base_pointer>(__ptr));
2392    return __r;
2393}
2394
2395#if _LIBCPP_STD_VER > 14
2396template <class _Tp, class _Compare, class _Allocator>
2397template <class _NodeHandle, class _InsertReturnType>
2398_LIBCPP_INLINE_VISIBILITY
2399_InsertReturnType
2400__tree<_Tp, _Compare, _Allocator>::__node_handle_insert_unique(
2401    _NodeHandle&& __nh)
2402{
2403    if (__nh.empty())
2404        return _InsertReturnType{end(), false, _NodeHandle()};
2405
2406    __node_pointer __ptr = __nh.__ptr_;
2407    __parent_pointer __parent;
2408    __node_base_pointer& __child = __find_equal(__parent,
2409                                                __ptr->__value_);
2410    if (__child != nullptr)
2411        return _InsertReturnType{
2412            iterator(static_cast<__node_pointer>(__child)),
2413            false, _VSTD::move(__nh)};
2414
2415    __insert_node_at(__parent, __child,
2416                     static_cast<__node_base_pointer>(__ptr));
2417    __nh.__release();
2418    return _InsertReturnType{iterator(__ptr), true, _NodeHandle()};
2419}
2420
2421template <class _Tp, class _Compare, class _Allocator>
2422template <class _NodeHandle>
2423_LIBCPP_INLINE_VISIBILITY
2424typename __tree<_Tp, _Compare, _Allocator>::iterator
2425__tree<_Tp, _Compare, _Allocator>::__node_handle_insert_unique(
2426    const_iterator __hint, _NodeHandle&& __nh)
2427{
2428    if (__nh.empty())
2429        return end();
2430
2431    __node_pointer __ptr = __nh.__ptr_;
2432    __parent_pointer __parent;
2433    __node_base_pointer __dummy;
2434    __node_base_pointer& __child = __find_equal(__hint, __parent, __dummy,
2435                                                __ptr->__value_);
2436    __node_pointer __r = static_cast<__node_pointer>(__child);
2437    if (__child == nullptr)
2438    {
2439        __insert_node_at(__parent, __child,
2440                         static_cast<__node_base_pointer>(__ptr));
2441        __r = __ptr;
2442        __nh.__release();
2443    }
2444    return iterator(__r);
2445}
2446
2447template <class _Tp, class _Compare, class _Allocator>
2448template <class _NodeHandle>
2449_LIBCPP_INLINE_VISIBILITY
2450_NodeHandle
2451__tree<_Tp, _Compare, _Allocator>::__node_handle_extract(key_type const& __key)
2452{
2453    iterator __it = find(__key);
2454    if (__it == end())
2455        return _NodeHandle();
2456    return __node_handle_extract<_NodeHandle>(__it);
2457}
2458
2459template <class _Tp, class _Compare, class _Allocator>
2460template <class _NodeHandle>
2461_LIBCPP_INLINE_VISIBILITY
2462_NodeHandle
2463__tree<_Tp, _Compare, _Allocator>::__node_handle_extract(const_iterator __p)
2464{
2465    __node_pointer __np = __p.__get_np();
2466    __remove_node_pointer(__np);
2467    return _NodeHandle(__np, __alloc());
2468}
2469
2470template <class _Tp, class _Compare, class _Allocator>
2471template <class _Tree>
2472_LIBCPP_INLINE_VISIBILITY
2473void
2474__tree<_Tp, _Compare, _Allocator>::__node_handle_merge_unique(_Tree& __source)
2475{
2476    static_assert(is_same<typename _Tree::__node_pointer, __node_pointer>::value, "");
2477
2478    for (typename _Tree::iterator __i = __source.begin();
2479         __i != __source.end();)
2480    {
2481        __node_pointer __src_ptr = __i.__get_np();
2482        __parent_pointer __parent;
2483        __node_base_pointer& __child =
2484            __find_equal(__parent, _NodeTypes::__get_key(__src_ptr->__value_));
2485        ++__i;
2486        if (__child != nullptr)
2487            continue;
2488        __source.__remove_node_pointer(__src_ptr);
2489        __insert_node_at(__parent, __child,
2490                         static_cast<__node_base_pointer>(__src_ptr));
2491    }
2492}
2493
2494template <class _Tp, class _Compare, class _Allocator>
2495template <class _NodeHandle>
2496_LIBCPP_INLINE_VISIBILITY
2497typename __tree<_Tp, _Compare, _Allocator>::iterator
2498__tree<_Tp, _Compare, _Allocator>::__node_handle_insert_multi(_NodeHandle&& __nh)
2499{
2500    if (__nh.empty())
2501        return end();
2502    __node_pointer __ptr = __nh.__ptr_;
2503    __parent_pointer __parent;
2504    __node_base_pointer& __child = __find_leaf_high(
2505        __parent, _NodeTypes::__get_key(__ptr->__value_));
2506    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__ptr));
2507    __nh.__release();
2508    return iterator(__ptr);
2509}
2510
2511template <class _Tp, class _Compare, class _Allocator>
2512template <class _NodeHandle>
2513_LIBCPP_INLINE_VISIBILITY
2514typename __tree<_Tp, _Compare, _Allocator>::iterator
2515__tree<_Tp, _Compare, _Allocator>::__node_handle_insert_multi(
2516    const_iterator __hint, _NodeHandle&& __nh)
2517{
2518    if (__nh.empty())
2519        return end();
2520
2521    __node_pointer __ptr = __nh.__ptr_;
2522    __parent_pointer __parent;
2523    __node_base_pointer& __child = __find_leaf(__hint, __parent,
2524                                               _NodeTypes::__get_key(__ptr->__value_));
2525    __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__ptr));
2526    __nh.__release();
2527    return iterator(__ptr);
2528}
2529
2530template <class _Tp, class _Compare, class _Allocator>
2531template <class _Tree>
2532_LIBCPP_INLINE_VISIBILITY
2533void
2534__tree<_Tp, _Compare, _Allocator>::__node_handle_merge_multi(_Tree& __source)
2535{
2536    static_assert(is_same<typename _Tree::__node_pointer, __node_pointer>::value, "");
2537
2538    for (typename _Tree::iterator __i = __source.begin();
2539         __i != __source.end();)
2540    {
2541        __node_pointer __src_ptr = __i.__get_np();
2542        __parent_pointer __parent;
2543        __node_base_pointer& __child = __find_leaf_high(
2544            __parent, _NodeTypes::__get_key(__src_ptr->__value_));
2545        ++__i;
2546        __source.__remove_node_pointer(__src_ptr);
2547        __insert_node_at(__parent, __child,
2548                         static_cast<__node_base_pointer>(__src_ptr));
2549    }
2550}
2551
2552#endif  // _LIBCPP_STD_VER > 14
2553
2554template <class _Tp, class _Compare, class _Allocator>
2555typename __tree<_Tp, _Compare, _Allocator>::iterator
2556__tree<_Tp, _Compare, _Allocator>::erase(const_iterator __p)
2557{
2558    __node_pointer __np = __p.__get_np();
2559    iterator __r = __remove_node_pointer(__np);
2560    __node_allocator& __na = __node_alloc();
2561    __node_traits::destroy(__na, _NodeTypes::__get_ptr(
2562        const_cast<__node_value_type&>(*__p)));
2563    __node_traits::deallocate(__na, __np, 1);
2564    return __r;
2565}
2566
2567template <class _Tp, class _Compare, class _Allocator>
2568typename __tree<_Tp, _Compare, _Allocator>::iterator
2569__tree<_Tp, _Compare, _Allocator>::erase(const_iterator __f, const_iterator __l)
2570{
2571    while (__f != __l)
2572        __f = erase(__f);
2573    return iterator(__l.__ptr_);
2574}
2575
2576template <class _Tp, class _Compare, class _Allocator>
2577template <class _Key>
2578typename __tree<_Tp, _Compare, _Allocator>::size_type
2579__tree<_Tp, _Compare, _Allocator>::__erase_unique(const _Key& __k)
2580{
2581    iterator __i = find(__k);
2582    if (__i == end())
2583        return 0;
2584    erase(__i);
2585    return 1;
2586}
2587
2588template <class _Tp, class _Compare, class _Allocator>
2589template <class _Key>
2590typename __tree<_Tp, _Compare, _Allocator>::size_type
2591__tree<_Tp, _Compare, _Allocator>::__erase_multi(const _Key& __k)
2592{
2593    pair<iterator, iterator> __p = __equal_range_multi(__k);
2594    size_type __r = 0;
2595    for (; __p.first != __p.second; ++__r)
2596        __p.first = erase(__p.first);
2597    return __r;
2598}
2599
2600template <class _Tp, class _Compare, class _Allocator>
2601template <class _Key>
2602typename __tree<_Tp, _Compare, _Allocator>::iterator
2603__tree<_Tp, _Compare, _Allocator>::find(const _Key& __v)
2604{
2605    iterator __p = __lower_bound(__v, __root(), __end_node());
2606    if (__p != end() && !value_comp()(__v, *__p))
2607        return __p;
2608    return end();
2609}
2610
2611template <class _Tp, class _Compare, class _Allocator>
2612template <class _Key>
2613typename __tree<_Tp, _Compare, _Allocator>::const_iterator
2614__tree<_Tp, _Compare, _Allocator>::find(const _Key& __v) const
2615{
2616    const_iterator __p = __lower_bound(__v, __root(), __end_node());
2617    if (__p != end() && !value_comp()(__v, *__p))
2618        return __p;
2619    return end();
2620}
2621
2622template <class _Tp, class _Compare, class _Allocator>
2623template <class _Key>
2624typename __tree<_Tp, _Compare, _Allocator>::size_type
2625__tree<_Tp, _Compare, _Allocator>::__count_unique(const _Key& __k) const
2626{
2627    __node_pointer __rt = __root();
2628    while (__rt != nullptr)
2629    {
2630        if (value_comp()(__k, __rt->__value_))
2631        {
2632            __rt = static_cast<__node_pointer>(__rt->__left_);
2633        }
2634        else if (value_comp()(__rt->__value_, __k))
2635            __rt = static_cast<__node_pointer>(__rt->__right_);
2636        else
2637            return 1;
2638    }
2639    return 0;
2640}
2641
2642template <class _Tp, class _Compare, class _Allocator>
2643template <class _Key>
2644typename __tree<_Tp, _Compare, _Allocator>::size_type
2645__tree<_Tp, _Compare, _Allocator>::__count_multi(const _Key& __k) const
2646{
2647    __iter_pointer __result = __end_node();
2648    __node_pointer __rt = __root();
2649    while (__rt != nullptr)
2650    {
2651        if (value_comp()(__k, __rt->__value_))
2652        {
2653            __result = static_cast<__iter_pointer>(__rt);
2654            __rt = static_cast<__node_pointer>(__rt->__left_);
2655        }
2656        else if (value_comp()(__rt->__value_, __k))
2657            __rt = static_cast<__node_pointer>(__rt->__right_);
2658        else
2659            return _VSTD::distance(
2660                __lower_bound(__k, static_cast<__node_pointer>(__rt->__left_), static_cast<__iter_pointer>(__rt)),
2661                __upper_bound(__k, static_cast<__node_pointer>(__rt->__right_), __result)
2662            );
2663    }
2664    return 0;
2665}
2666
2667template <class _Tp, class _Compare, class _Allocator>
2668template <class _Key>
2669typename __tree<_Tp, _Compare, _Allocator>::iterator
2670__tree<_Tp, _Compare, _Allocator>::__lower_bound(const _Key& __v,
2671                                                 __node_pointer __root,
2672                                                 __iter_pointer __result)
2673{
2674    while (__root != nullptr)
2675    {
2676        if (!value_comp()(__root->__value_, __v))
2677        {
2678            __result = static_cast<__iter_pointer>(__root);
2679            __root = static_cast<__node_pointer>(__root->__left_);
2680        }
2681        else
2682            __root = static_cast<__node_pointer>(__root->__right_);
2683    }
2684    return iterator(__result);
2685}
2686
2687template <class _Tp, class _Compare, class _Allocator>
2688template <class _Key>
2689typename __tree<_Tp, _Compare, _Allocator>::const_iterator
2690__tree<_Tp, _Compare, _Allocator>::__lower_bound(const _Key& __v,
2691                                                 __node_pointer __root,
2692                                                 __iter_pointer __result) const
2693{
2694    while (__root != nullptr)
2695    {
2696        if (!value_comp()(__root->__value_, __v))
2697        {
2698            __result = static_cast<__iter_pointer>(__root);
2699            __root = static_cast<__node_pointer>(__root->__left_);
2700        }
2701        else
2702            __root = static_cast<__node_pointer>(__root->__right_);
2703    }
2704    return const_iterator(__result);
2705}
2706
2707template <class _Tp, class _Compare, class _Allocator>
2708template <class _Key>
2709typename __tree<_Tp, _Compare, _Allocator>::iterator
2710__tree<_Tp, _Compare, _Allocator>::__upper_bound(const _Key& __v,
2711                                                 __node_pointer __root,
2712                                                 __iter_pointer __result)
2713{
2714    while (__root != nullptr)
2715    {
2716        if (value_comp()(__v, __root->__value_))
2717        {
2718            __result = static_cast<__iter_pointer>(__root);
2719            __root = static_cast<__node_pointer>(__root->__left_);
2720        }
2721        else
2722            __root = static_cast<__node_pointer>(__root->__right_);
2723    }
2724    return iterator(__result);
2725}
2726
2727template <class _Tp, class _Compare, class _Allocator>
2728template <class _Key>
2729typename __tree<_Tp, _Compare, _Allocator>::const_iterator
2730__tree<_Tp, _Compare, _Allocator>::__upper_bound(const _Key& __v,
2731                                                 __node_pointer __root,
2732                                                 __iter_pointer __result) const
2733{
2734    while (__root != nullptr)
2735    {
2736        if (value_comp()(__v, __root->__value_))
2737        {
2738            __result = static_cast<__iter_pointer>(__root);
2739            __root = static_cast<__node_pointer>(__root->__left_);
2740        }
2741        else
2742            __root = static_cast<__node_pointer>(__root->__right_);
2743    }
2744    return const_iterator(__result);
2745}
2746
2747template <class _Tp, class _Compare, class _Allocator>
2748template <class _Key>
2749pair<typename __tree<_Tp, _Compare, _Allocator>::iterator,
2750     typename __tree<_Tp, _Compare, _Allocator>::iterator>
2751__tree<_Tp, _Compare, _Allocator>::__equal_range_unique(const _Key& __k)
2752{
2753    typedef pair<iterator, iterator> _Pp;
2754    __iter_pointer __result = __end_node();
2755    __node_pointer __rt = __root();
2756    while (__rt != nullptr)
2757    {
2758        if (value_comp()(__k, __rt->__value_))
2759        {
2760            __result = static_cast<__iter_pointer>(__rt);
2761            __rt = static_cast<__node_pointer>(__rt->__left_);
2762        }
2763        else if (value_comp()(__rt->__value_, __k))
2764            __rt = static_cast<__node_pointer>(__rt->__right_);
2765        else
2766            return _Pp(iterator(__rt),
2767                      iterator(
2768                          __rt->__right_ != nullptr ?
2769                              static_cast<__iter_pointer>(__tree_min(__rt->__right_))
2770                            : __result));
2771    }
2772    return _Pp(iterator(__result), iterator(__result));
2773}
2774
2775template <class _Tp, class _Compare, class _Allocator>
2776template <class _Key>
2777pair<typename __tree<_Tp, _Compare, _Allocator>::const_iterator,
2778     typename __tree<_Tp, _Compare, _Allocator>::const_iterator>
2779__tree<_Tp, _Compare, _Allocator>::__equal_range_unique(const _Key& __k) const
2780{
2781    typedef pair<const_iterator, const_iterator> _Pp;
2782    __iter_pointer __result = __end_node();
2783    __node_pointer __rt = __root();
2784    while (__rt != nullptr)
2785    {
2786        if (value_comp()(__k, __rt->__value_))
2787        {
2788            __result = static_cast<__iter_pointer>(__rt);
2789            __rt = static_cast<__node_pointer>(__rt->__left_);
2790        }
2791        else if (value_comp()(__rt->__value_, __k))
2792            __rt = static_cast<__node_pointer>(__rt->__right_);
2793        else
2794            return _Pp(const_iterator(__rt),
2795                      const_iterator(
2796                          __rt->__right_ != nullptr ?
2797                              static_cast<__iter_pointer>(__tree_min(__rt->__right_))
2798                            : __result));
2799    }
2800    return _Pp(const_iterator(__result), const_iterator(__result));
2801}
2802
2803template <class _Tp, class _Compare, class _Allocator>
2804template <class _Key>
2805pair<typename __tree<_Tp, _Compare, _Allocator>::iterator,
2806     typename __tree<_Tp, _Compare, _Allocator>::iterator>
2807__tree<_Tp, _Compare, _Allocator>::__equal_range_multi(const _Key& __k)
2808{
2809    typedef pair<iterator, iterator> _Pp;
2810    __iter_pointer __result = __end_node();
2811    __node_pointer __rt = __root();
2812    while (__rt != nullptr)
2813    {
2814        if (value_comp()(__k, __rt->__value_))
2815        {
2816            __result = static_cast<__iter_pointer>(__rt);
2817            __rt = static_cast<__node_pointer>(__rt->__left_);
2818        }
2819        else if (value_comp()(__rt->__value_, __k))
2820            __rt = static_cast<__node_pointer>(__rt->__right_);
2821        else
2822            return _Pp(__lower_bound(__k, static_cast<__node_pointer>(__rt->__left_), static_cast<__iter_pointer>(__rt)),
2823                      __upper_bound(__k, static_cast<__node_pointer>(__rt->__right_), __result));
2824    }
2825    return _Pp(iterator(__result), iterator(__result));
2826}
2827
2828template <class _Tp, class _Compare, class _Allocator>
2829template <class _Key>
2830pair<typename __tree<_Tp, _Compare, _Allocator>::const_iterator,
2831     typename __tree<_Tp, _Compare, _Allocator>::const_iterator>
2832__tree<_Tp, _Compare, _Allocator>::__equal_range_multi(const _Key& __k) const
2833{
2834    typedef pair<const_iterator, const_iterator> _Pp;
2835    __iter_pointer __result = __end_node();
2836    __node_pointer __rt = __root();
2837    while (__rt != nullptr)
2838    {
2839        if (value_comp()(__k, __rt->__value_))
2840        {
2841            __result = static_cast<__iter_pointer>(__rt);
2842            __rt = static_cast<__node_pointer>(__rt->__left_);
2843        }
2844        else if (value_comp()(__rt->__value_, __k))
2845            __rt = static_cast<__node_pointer>(__rt->__right_);
2846        else
2847            return _Pp(__lower_bound(__k, static_cast<__node_pointer>(__rt->__left_), static_cast<__iter_pointer>(__rt)),
2848                      __upper_bound(__k, static_cast<__node_pointer>(__rt->__right_), __result));
2849    }
2850    return _Pp(const_iterator(__result), const_iterator(__result));
2851}
2852
2853template <class _Tp, class _Compare, class _Allocator>
2854typename __tree<_Tp, _Compare, _Allocator>::__node_holder
2855__tree<_Tp, _Compare, _Allocator>::remove(const_iterator __p) _NOEXCEPT
2856{
2857    __node_pointer __np = __p.__get_np();
2858    if (__begin_node() == __p.__ptr_)
2859    {
2860        if (__np->__right_ != nullptr)
2861            __begin_node() = static_cast<__iter_pointer>(__np->__right_);
2862        else
2863            __begin_node() = static_cast<__iter_pointer>(__np->__parent_);
2864    }
2865    --size();
2866    __tree_remove(__end_node()->__left_,
2867                  static_cast<__node_base_pointer>(__np));
2868    return __node_holder(__np, _Dp(__node_alloc(), true));
2869}
2870
2871template <class _Tp, class _Compare, class _Allocator>
2872inline _LIBCPP_INLINE_VISIBILITY
2873void
2874swap(__tree<_Tp, _Compare, _Allocator>& __x,
2875     __tree<_Tp, _Compare, _Allocator>& __y)
2876    _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
2877{
2878    __x.swap(__y);
2879}
2880
2881_LIBCPP_END_NAMESPACE_STD
2882
2883_LIBCPP_POP_MACROS
2884
2885#endif  // _LIBCPP___TREE
2886