STL之rb_tree的find函数


1 通用的search方法

STL在实现对特定key值的查找时,并没有採用通用的方法:

BRTreeNode *  rb_tree_search(RBTreeNode * x, int key){
	while(x ! = NULL && x->key != key){
		if( x->key > key){
			x = x ->left;
		}else{
			x = x->right;
		}
	}
	return x;
}
假设rb_tree树中同意多个同样的key同一时候存在.上述方法查找到的是中序顺序中的位置最后的那个,

假设要求要求查找的是中序顺序中的第一个出现的位置呢?

看看STL是怎么实现的.

2 find源代码

template<typename _Key, typename _Val, typename _KeyOfValue,
           typename _Compare, typename _Alloc>
    typename _Rb_tree<_Key, _Val, _KeyOfValue,
		      _Compare, _Alloc>::iterator
    _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
    find(const _Key& __k)
    {
      iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k);
      return (__j == end()
	      || _M_impl._M_key_compare(__k,
					_S_key(__j._M_node))) ?

end() : __j; }


STL採用的lower_bound函数实现.若干j指向end()或k 比j的值还小则不存在.


3 lower_bound源代码

template<typename _Key, typename _Val, typename _KeyOfValue,
           typename _Compare, typename _Alloc>
    typename _Rb_tree<_Key, _Val, _KeyOfValue,
		      _Compare, _Alloc>::const_iterator
    _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
    _M_lower_bound(_Const_Link_type __x, _Const_Link_type __y,
		   const _Key& __k) const
    {
      while (__x != 0)
	if (!_M_impl._M_key_compare(_S_key(__x), __k))//__x >= k
	  __y = __x, __x = _S_left(__x);
	else
	  __x = _S_right(__x);
      return const_iterator(__y);
    }

引入一个y变量,记录中序顺序中第一个比k大或相等的位置.
假设要找最大的位置呢.自然的想到upper_bound函数.怎么实现?

4 upper_bound源代码


  template<typename _Key, typename _Val, typename _KeyOfValue,
           typename _Compare, typename _Alloc>
    typename _Rb_tree<_Key, _Val, _KeyOfValue,
		      _Compare, _Alloc>::iterator
    _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
    _M_upper_bound(_Link_type __x, _Link_type __y,
		   const _Key& __k)
    {
      while (__x != 0)
	if (_M_impl._M_key_compare(__k, _S_key(__x)))//__x > k
	  __y = __x, __x = _S_left(__x);
	else
	  __x = _S_right(__x);
      return iterator(__y);
    }



原文地址:https://www.cnblogs.com/cynchanpin/p/7111030.html