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