std::map和std::mulitmap的简单实现
std::map的实现
template <typename Pair> struct Select1st_ { const typename Pair::first_type& operator()(const Pair& x) const { return x.first; } }; template <typename Key, typename Tp, typename Compare = std::less<Key>> class Mymap { typedef Key key_type; typedef Tp data_type; typedef std::pair<Key, Tp> value_type; private: typedef Rb_tree<key_type, value_type, Select1st_<value_type>, Compare> Rep_type; Rep_type m_rbtree; public: typedef typename Rep_type::iterator iterator; typedef typename Rep_type::size_type size_type; Mymap() : m_rbtree() {} Mymap(Mymap&& x) : m_rbtree(std::move(x.m_rbtree)) {} iterator begin() { return m_rbtree.begin(); } iterator end() { return m_rbtree.end(); } bool empty() const { return m_rbtree.empty(); } size_type size() const { return m_rbtree.size(); } Tp& operator[](const key_type& k) {// 如果下标key值不存在,就新插入一个默认构造值 iterator i = m_rbtree.lower_bound(k); if (i == end() || Compare()(k, (*i).first)) { std::pair<iterator, bool> ret = insert(value_type(k, Tp())); return (*(ret.first)).second; } return (*i).second; } void swap(Mymap& x) { m_rbtree.swap(x.m_rbtree); } std::pair<iterator, bool> insert(const value_type& x) { return m_rbtree.insert_unique(x); } void erase(iterator position) { m_rbtree.erase(position); } size_type erase(const key_type& x) { return m_rbtree.erase(x); } void clear() { m_rbtree.clear(); } iterator find(const key_type& x) { return m_rbtree.find(x); } size_type count(const key_type& x) const { return m_rbtree.count(x); } iterator lower_bound(const key_type& x) { return m_rbtree.lower_bound(x); } iterator upper_bound(const key_type& x) { return m_rbtree.upper_bound(x); } };
std::multimap
template <typename Key, typename Tp, typename Compare = std::less<Key>> class Mymultimap { public: typedef Key key_type; typedef Tp data_type; typedef std::pair<Key, Tp> value_type; private: typedef Rb_tree<key_type, value_type, Select1st_<value_type>, Compare> Rep_type; Rep_type m_rbtree; public: typedef typename Rep_type::iterator iterator; typedef typename Rep_type::size_type size_type; Mymultimap() : m_rbtree() {} Mymultimap(Mymultimap&& x) : m_rbtree(std::move(x.m_rbtree)) {} iterator begin() { return m_rbtree.begin(); } iterator end() { return m_rbtree.end(); } bool empty() const { return m_rbtree.empty(); } size_type size() const { return m_rbtree.size(); } void swap(Mymultimap& x) { m_rbtree.swap(x.m_rbtree); } iterator insert(const value_type& x) { return m_rbtree.insert_equal(x); } void erase(iterator position) { m_rbtree.erase(position); } size_type erase(const key_type& x) { return m_rbtree.erase(x); } void clear() { m_rbtree.clear(); } iterator find(const key_type& x) { return m_rbtree.find(x); } size_type count(const key_type& x) const { return m_rbtree.count(x); } };