set容器是以红黑树容器为基础实现的,在其基础上稍加改变接口即可
#ifndef MY_SET_H_INCLUDED #define MY_SET_H_INCLUDED #include"my_rb_tree.h" namespace juine { template<typename T> struct identity { const T& operator()(const T& x) { return x; } }; template<class T> struct comp { bool operator()(T v1,T v2) { return v1<v2; } }; template<class Key,class Compare=comp<Key>,class Alloc=my_alloc> class my_set { public: typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef RB_Tree<Key,Key,identity<Key>,Compare,Alloc > rep_type; protected: //set底层就是依赖红黑树实现的 rep_type rb_tree; public: //使用红黑树的迭代器,而不自己重新定义迭代器 typedef typename rep_type::const_iterator iterator; //construct my_set(){} //set容器中不准出现同样的元素 //故不存在构造函数set(size_t,value) template<class InputIterator> my_set(InputIterator first,InputIterator last) { /* 该函数的实现,和以前的容器差不多,在此就不实现了 */ } iterator begin() { return rb_tree.begin(); } iterator end() { return rb_tree.end(); } void insert(value_type value) { rb_tree.insert_node(value); } void erase(iterator pos) { rb_tree.delete_node(*pos); } iterator lower_bound(value_type value) { return rb_tree.lower_bound(value); } iterator upper_bound(value_type value) { return rb_tree.upper_bound(value); } iterator find(value_type value) { return iterator(rb_tree.find_node(value),rb_tree.get_nullNode()); } }; } #endif // MY_SET_H_INCLUDED
#include"my_set.h" #include<iostream> using namespace std; using namespace juine; int main() { my_set<int> s; int i; for(i=1;i<10;i++) s.insert(i); my_set<int >::iterator iter=s.begin(); for(iter=s.begin();iter!=s.end();iter++) cout<<*iter<<endl; iter=s.find(6); cout<<*iter<<endl; return 0; }
原文地址:http://blog.csdn.net/bb2b2bbb/article/details/24666359