实现一个map模版,能够实现以下的功能:
1.能在o(lgn)时间内,实现按key 值的添加,删除,查找。
2.能在o(lgn)时间内,实现按value 值排名的增删查
代码如下:
#include<iostream>
#include<string>
using namespace std;
//∂®“Â∫Ï∫⁄÷µ
const int RED =1;
const int BLACK =0;
template<typename K,typename V>
struct K_Value
{
K_Value():first(K()),second(V()){}
K_Value(const K &k,const V &v):first(k),second(v){}
K first; //÷∏œÚπÿº¸◊÷
V second; //÷∏œÚ÷µ
};
//∂®“ ˜Ω⁄µ„
template<typename T,typename V>
struct RBNode{
RBNode():left(NULL),right(NULL),parent(NULL),key(T()),value(V()),color(RED),l_child_nums(0),r_child_nums(0){}
RBNode(const T &v1,const V& v2):left(NULL),right(NULL),parent(NULL),key(v1),value(v2),color(RED),l_child_nums(0),r_child_nums(0){}
T key;
V value;
RBNode * left;
RBNode * right;
int color;
RBNode * parent;
int l_child_nums; //±»µ±«∞Ω⁄µ„–°µƒ∫¢◊”∏ˆ ˝
int r_child_nums; //±»µ±«∞Ω⁄µ„¥Ûµƒ∫¢◊”Ω⁄µ„∏ˆ ˝
};
//∂®“ƒ£∞Â
template <typename T,typename V> class Find_Map{
public:
Find_Map()
{
Nil = new RBNode<T,V>;
Nil->parent = Nil;
Nil->color = BLACK;
//Nil->key = NULL;
Nil->l_child_nums = 0;
Nil->r_child_nums = 0;
Nil->left = Nil;
Nil->right = Nil;
root = Nil;
}
//Œˆππ∫Ø ˝
~Find_Map()
{
delete Nil;
Nil = NULL;
root = NULL;
}
void RB_Create( K_Value<T,V> a[],int length ); //¥¥Ω®∫Ï∫⁄ ˜
void Delete(const T &key); //∞¥÷µ…æ≥˝
void Insert(const K_Value<T,V> &key); //∞¥÷µÃ̺”
K_Value<T,V> Search(const T &v1); //∞¥key≤È’“
K_Value<T,V> RankSearch(int rank); //∞¥≈≈√˚≤È’“
private:
RBNode<T,V> * TreeSuccessor(RBNode<T,V> * x);
void InsertReBalance(RBNode<T,V> * node); //≤»Î∫ÛΩ´ ˜≈™≥…∆Ω∫‚ ˜
void DeleteReBalance(RBNode<T,V> * node); //…æ≥˝∫ÛΩ´ ˜≈™≥…∆Ω∫‚ ˜
void _rotate_left(RBNode<T,V> * node); //◊Û–˝≤Ÿ◊˜
void _rotate_right(RBNode<T,V> * node); //”“–˝≤Ÿ◊˜
RBNode<T,V> * root;
RBNode<T,V> * Nil; //…Ë÷√…⁄±¯
};
//∞¥÷µ≤È’“
template<typename T,typename V>
K_Value<T,V> Find_Map<T,V>:: Search(const T& value)
{
//∏˘æ›typeµƒ¿‡–Õæˆ∂® «‘ˆº”ªπ «…æ≥˝ªÚ’fl≤ª∂Ø
RBNode<T,V> * p = root;
while(p != Nil && p->key != value)
{
if(p->key == value)
{
return K_Value<T,V>(p->key,p->value);
break;
}
//œÚ◊Û≤È’“
elseif(p->key < value)
{
p = p->right;
}
//œÚ”“≤È’“
else
{
p = p->left;
}
}
if(p->key == value)
{
return K_Value<T,V>(p->key,p->value);
}
return K_Value<T,V>();
}
// µœ÷∞¥≈≈√˚≤È’“
template<typename T,typename V>
K_Value<T,V> Find_Map<T,V>::RankSearch(int rank)
{
RBNode<T,V> * p = root;