标签:tracking pre null turn ons style tor com amp
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是怎么实现的.
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;
}
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函数.怎么实现?
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);
}
标签:tracking pre null turn ons style tor com amp
原文地址:http://www.cnblogs.com/cynchanpin/p/7111030.html