├── RBtreeIterator.h ├── README.md ├── _vector.cpp ├── algorithm.h ├── alloc.cpp ├── alloc.h ├── allocator.h ├── construct.h ├── deque.h ├── dequeIterator.h ├── error ├── error0116.txt ├── error0117.txt ├── error0118.txt ├── error0709-2.txt ├── error0709.txt └── error0814.txt ├── functional.h ├── impl └── deque.impl.h ├── iterator.h ├── list.h ├── listIterator.h ├── listNode.h ├── main.cpp ├── makefile ├── map.h ├── mapTest.o ├── pair.h ├── pic ├── STL文件关系树.png └── STL文件关系树.xmind ├── rbtree.h ├── set.h ├── test ├── dequeTest.cpp ├── dequeTest.h ├── heapTest.cpp ├── heapTest.h ├── listTest.cpp ├── listTest.h ├── mapTest.cpp ├── mapTest.h ├── rbtreeTest.cpp ├── rbtreeTest.h ├── setTest.cpp ├── setTest.h ├── testFun.h ├── vectorTest.cpp └── vectorTest.h ├── typetraits.h ├── uninitialized.h └── vector.h /RBtreeIterator.h: -------------------------------------------------------------------------------- 1 | #ifndef _RBTREE_H_ 2 | #define _RBTREE_H_ 3 | 4 | #include "iterator.h" 5 | 6 | namespace EasySTL { 7 | typedef bool __rb_tree_color_type; 8 | const __rb_tree_color_type __rb_tree_red = false; 9 | const __rb_tree_color_type __rb_tree_black = true; 10 | 11 | struct __rb_tree_node_base { 12 | typedef __rb_tree_color_type color_type; 13 | typedef __rb_tree_node_base* base_ptr; 14 | 15 | color_type color; 16 | base_ptr parent; 17 | base_ptr left; 18 | base_ptr right; 19 | static base_ptr minimum(base_ptr x) { 20 | while (x->left != 0) x=x->left; 21 | return x; 22 | } 23 | 24 | static base_ptr maximum(base_ptr x) { 25 | while (x->right != 0) x=x->right; 26 | return x; 27 | } 28 | }; 29 | 30 | template 31 | struct __rb_tree_node : public __rb_tree_node_base { 32 | typedef __rb_tree_node* link_type; 33 | Value value_field; 34 | }; 35 | 36 | struct __rb_tree_base_iterator { 37 | typedef __rb_tree_node_base::base_ptr base_ptr; 38 | typedef bidirectional_iterator_tag iterator_category; 39 | typedef ptrdiff_t difference_type; 40 | base_ptr node;//make a reference 41 | 42 | void increment() { 43 | if (node->right != 0) { 44 | node = node->right; 45 | while(node->left != 0) node = node->left; 46 | } else { 47 | base_ptr y = node->parent;//父节点不一定大于自己 48 | while(node == y->right) { 49 | node = y; 50 | y = y->parent; 51 | } 52 | if (node->right != y) 53 | node = y; 54 | } 55 | } 56 | void decrement() { 57 | if (node->color == __rb_tree_red && 58 | node->parent->parent == node) 59 | node = node->right; 60 | else if (node->left != 0) { 61 | base_ptr y = node->left; 62 | while(y->right != 0) y = y->right; 63 | node = y; 64 | } else { 65 | base_ptr y = node->parent; 66 | while (node == y->left) { 67 | node = y; 68 | y = y->parent; 69 | } 70 | node = y; 71 | } 72 | } 73 | }; 74 | 75 | template 76 | struct __rb_tree_iterator : public __rb_tree_base_iterator { 77 | typedef Value value_type; 78 | typedef Ref reference; 79 | typedef Ptr pointer; 80 | typedef __rb_tree_iterator iterator; 81 | typedef __rb_tree_iterator const_iterator; 82 | typedef __rb_tree_iterator self; 83 | typedef __rb_tree_node* link_type; 84 | 85 | __rb_tree_iterator() {} 86 | __rb_tree_iterator(link_type x) {node = x;} 87 | __rb_tree_iterator(const iterator& it) { node = it.node;} 88 | 89 | reference operator*() const { return link_type(node)->value_field;} 90 | pointer operator->() const { return &(operator*());} 91 | 92 | self& operator++() {increment(); return *this;} 93 | self operator++(int) { 94 | self tmp = *this; 95 | increment(); 96 | return tmp; 97 | } 98 | 99 | self& operator--() { decrement(); return *this;} 100 | self operator--(int) { 101 | self tmp = *this; 102 | decrement(); 103 | return tmp; 104 | } 105 | 106 | bool operator==(const self& iter) const { return node == iter.node;} 107 | bool operator!=(const self& iter) const { return node != iter.node;} 108 | 109 | // bool operator==(const self& x) const {return node == x.node;} 110 | // bool operator!=(const self& x) const {return node != x.node;} 111 | }; 112 | } 113 | #endif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasySTL,实现自己的STL 2 | 3 | 学习C++离不开学习STL,除了阅读经典的《STL源码剖析》,也要自己动手编写代码。该项目将持续更新,这也是我未来几个月实习空闲时间要做的事,加油~ 4 | 5 | 2017.01.18 EasySTL就以Map的实现年前暂时告一段落,谢谢各位的支持 6 | **鸡年规划:周末时间,部分algorithm的实现,复习前面的内存配置,迭代器的实现,好好理解模板编程** 7 | ------------- 8 | ### 要点 9 | - **c++11** 10 | - **g++ makefile编写** 11 | - **c++ google code style** 12 | - **模板编程** 13 | - **内存管理,数据结构** 14 | 15 | ------------------- 16 | ###STL文件关系树 17 | 18 | ![关系树](https://github.com/hunterzhao/EasySTL/blob/master/pic/STL%E6%96%87%E4%BB%B6%E5%85%B3%E7%B3%BB%E6%A0%91.png?raw=true) 19 | 20 | ------------------- 21 | 22 | ### 环境 23 | - ubuntu 14.04 24 | - g++ 4.8.8 25 | - sublime 26 | - c++11 27 | 28 | ------------------- 29 | ###使用 30 | 1. 下载代码[Github][1]. 如果有帮助请帮我点star :) 31 | 2. main.cpp可以修改要测试的容器或算法 32 | 3. 根目录下运行 make 33 | 4. 运行test.exe 34 | 35 | ------------------- 36 | ###TODO Continue... 37 | 38 | >基本 39 | 40 | 1. allocator 空间配置器 done 41 | 2. typetraits 类型萃取器 done 42 | 3. iterator 迭代器 done 43 | 4. construct 对象构造器 done 44 | 5. alogritm 算法库 doing 45 | 6. unitialized 容器构造器 done 46 | 47 | >容器 48 | 49 | 1. vector done 2016.7.09 done 50 | 2. list done 2016.7.23 done 51 | 3. string 52 | 4. deque 2016.12.24 done 53 | 5. set 2017.01.17 done 54 | 6. map 2017.01.18 done 55 | 56 | 57 | >算法 58 | 59 | 1. heap done 60 | 2. rbtree done 61 | 3. Qsort TODO 62 | 4. 63 | ------------------- 64 | ###测试 65 | 1. vector 构造功能,列表初始化,插入功能,clear功能,迭代器功能 ok 66 | 2. list 构造功能,插入功能,clear功能,迭代器功能,reverse, merge, sort(插入排序) ok 67 | 68 | 69 | 70 | --------- 71 | [1]: https://github.com/hunterzhao/EasySTL 72 | -------------------------------------------------------------------------------- /_vector.cpp: -------------------------------------------------------------------------------- 1 | #include "vector.h" 2 | 3 | namespace EasySTL { 4 | 5 | template 6 | void vector::insert_aux(iterator position, const T& x) { 7 | if (finish_ != end_of_storage_) { 8 | //还有备用空间 9 | //在备用空间开始处创建一个对象,并以vector的最后一个对象为初始值 10 | construct(finish_, *(finish_ - 1)); 11 | ++finish_; 12 | T x_copy = x; 13 | copy_backward(position, finish_ - 2, finish_ - 1); 14 | *position = x_copy; //position上是已经有构造好的对象,直接赋值就可以 15 | } else { 16 | //没有可用空间 17 | const size_type old_size = size(); 18 | //内存不足则申请原来两倍的新内存 19 | const size_type new_size = old_size != 0 ? 2 * old_size : 1; 20 | 21 | iterator new_start = data_allocator::allocate(new_size); 22 | iterator new_finish = new_start; 23 | try { 24 | new_finish = uninitialized_copy(start_, position, new_start); 25 | construct(new_finish ,x); //未构造的内存,需要调用construct 26 | new_finish++; 27 | new_finish = uninitialized_copy(position, finish_, new_finish); 28 | } catch (...) { 29 | //出现异常,回滚 30 | destroy(new_start, new_finish); 31 | data_allocator::deallocate(new_start, new_size); 32 | throw; 33 | } 34 | 35 | destroy(begin(), end());//销毁原来的vector内存空间 36 | deallocate(); 37 | 38 | start_ = new_start; 39 | finish_ = new_finish; 40 | end_of_storage_ = new_start + new_size; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /algorithm.h: -------------------------------------------------------------------------------- 1 | #ifndef _ALGORITHM_H_ 2 | #define _ALGORITHM_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include "iterator.h" 8 | #include "typetraits.h" 9 | namespace EasySTL { 10 | //***** fill O(N)****** 11 | template 12 | void fill(ForwardIterator first, ForwardIterator last, const T& value) { 13 | for (; first != last; ++first) 14 | *first = value; 15 | } 16 | 17 | inline void fill(char *first, char *last, const char& value) { 18 | memset(first, static_cast(value), last - first); 19 | } 20 | 21 | inline void fill(wchar_t *first, wchar_t *last, const wchar_t& value) { 22 | memset(first, static_cast(value), (last - first) * sizeof(wchar_t)); 23 | } 24 | 25 | //***** fill_n O(N)****** 26 | template 27 | OutputIterator fill_n(OutputIterator first, Size n, const T& value) { 28 | for (; n > 0; --n, ++first) 29 | *first = value; 30 | return first; 31 | } 32 | 33 | template 34 | char *fill_n(char *first, Size n, const char& value) { 35 | memset(first, static_cast(value), n); 36 | return first + n; 37 | } 38 | 39 | template 40 | wchar_t *fill_n(wchar_t *first, Size n, const wchar_t& value) { 41 | memset(first, static_cast(value), n * sizeof(wchar_t)); 42 | return first + n; 43 | } 44 | 45 | //********** [distance] ****************************** 46 | 47 | //********* [Algorithm Complexity: O(N)] **************** 48 | 49 | template 50 | typename iterator_traits::difference_type 51 | 52 | _distance(InputIterator first, InputIterator last, input_iterator_tag){ 53 | typename iterator_traits::difference_type dist = 0; 54 | while (first++ != last){ 55 | ++dist; 56 | } 57 | 58 | return dist; 59 | 60 | } 61 | 62 | template 63 | typename iterator_traits::difference_type 64 | 65 | _distance(RandomIterator first, RandomIterator last, random_access_iterator_tag){ 66 | 67 | auto dist = last - first; 68 | 69 | return dist; 70 | 71 | } 72 | 73 | template 74 | typename iterator_traits::difference_type 75 | 76 | distance(Iterator first, Iterator last){ 77 | typedef typename iterator_traits::iterator_category iterator_category; 78 | return _distance(first, last, iterator_category()); 79 | 80 | } 81 | 82 | //********** [push_heap] ****************************** 83 | template 84 | inline void __push_heap(RandomAccessIterator first, Distance holeIndex, Distance topIndex, T value) { 85 | Distance parent = (holeIndex-1) / 2; 86 | while(holeIndex > topIndex && *(first + parent) < value) { 87 | *(first + holeIndex) = *(first + parent);//父节点的值下降 88 | holeIndex = parent; 89 | parent = (holeIndex - 1) / 2; //找下一个父节点位置 90 | } 91 | *(first + holeIndex) = value; // 92 | } 93 | 94 | template 95 | inline void __push_heap_aux(RandomAccessIterator first, RandomAccessIterator last, 96 | Distance *, T*) { 97 | EasySTL::__push_heap(first, Distance((last - first) - 1), Distance(0), T(*(last - 1))); 98 | } 99 | 100 | template 101 | inline void push_heap(RandomAccessIterator first, RandomAccessIterator last) { 102 | //新元素已经位于底部容器的最尾端 103 | EasySTL::__push_heap_aux(first, last, difference_type(first), value_type(first)); 104 | } 105 | 106 | //********** [pop_heap] ****************************** 107 | //将最大值放到末尾 108 | template 109 | void __adjust_heap(RandomAccessIterator first, Distance holeIndex, 110 | Distance len, T value) { 111 | Distance topIndex = holeIndex; 112 | Distance secondChild = 2*holeIndex + 2; 113 | while(secondChild < len) { 114 | //比较洞的左右孩子,然后以secondChild 代表较大节点 115 | if (*(first + secondChild) < *(first + (secondChild - 1))) 116 | secondChild--; 117 | //较大的孩子作为洞值,洞下移至较大子节点处 118 | *(first + holeIndex) = *(first + secondChild); 119 | holeIndex = secondChild; 120 | secondChild = 2 * (secondChild + 1); 121 | } 122 | if(secondChild == len) {//没有右节点只有左节点 123 | *(first + holeIndex) = *(first + (secondChild - 1)); 124 | holeIndex = secondChild - 1; 125 | } 126 | EasySTL::__push_heap(first, holeIndex, topIndex, value); 127 | } 128 | 129 | template 130 | inline void __pop_heap(RandomAccessIterator first, RandomAccessIterator last, 131 | RandomAccessIterator result, T value, Distance*) { 132 | *result = *first; 133 | EasySTL::__adjust_heap(first, Distance(0), Distance(last - first), value);//value 暂时保存 134 | } 135 | 136 | template 137 | inline void __pop_heap_aux(RandomAccessIterator first, RandomAccessIterator last, T*) { 138 | EasySTL::__pop_heap(first, last-1, last-1, T(*(last-1)), difference_type(first)); 139 | } 140 | 141 | template 142 | inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last) { 143 | EasySTL::__pop_heap_aux(first, last, value_type(first)); 144 | } 145 | 146 | //********** [pop_heap] ****************************** 147 | template 148 | void __make_heap(RandomIterator first, 149 | RandomIterator last, T*, Distance*) { 150 | if(last- first<2) return; 151 | Distance len = last - first; 152 | Distance parent = (len -2)/2; 153 | while(true) {//调整整个树的所有父节点 154 | EasySTL::__adjust_heap(first, parent, len, T(*(first + parent))); 155 | if (parent == 0) return; 156 | parent--; 157 | } 158 | } 159 | 160 | template 161 | inline void make_heap(RandomIterator first, RandomIterator last) { 162 | EasySTL::__make_heap(first, last, value_type(first), difference_type(first)); 163 | } 164 | 165 | 166 | //********** [advance] ****************************** 167 | //********* [Algorithm Complexity: O(N)] **************** 168 | template 169 | void _advance(InputIterator& it, Distance n, input_iterator_tag){ 170 | assert(n >= 0); 171 | while (n--){ 172 | ++it; 173 | } 174 | } 175 | template 176 | void _advance(BidirectionIterator& it, Distance n, bidirectional_iterator_tag){ 177 | if (n < 0){ 178 | while (n++){ 179 | --it; 180 | } 181 | }else{ 182 | while (n--){ 183 | ++it; 184 | } 185 | } 186 | } 187 | template 188 | void _advance(RandomIterator& it, Distance n, random_access_iterator_tag){ 189 | if (n < 0){ 190 | it -= (-n); 191 | }else{ 192 | it += n; 193 | } 194 | } 195 | 196 | template 197 | void advance(InputIterator& it, Distance n){ 198 | typedef typename iterator_traits::iterator_category iterator_category; 199 | _advance(it, n, iterator_category()); 200 | } 201 | 202 | //********** [copy] ****************************** 203 | 204 | //********* [Algorithm Complexity: O(N)] **************** 205 | 206 | template 207 | OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, _true_type){ 208 | 209 | auto dist = distance(first, last); 210 | memcpy(result, first, sizeof(*first) * dist); 211 | advance(result, dist); 212 | return result; 213 | 214 | } 215 | 216 | template 217 | OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, _false_type){ 218 | 219 | while (first != last){ 220 | *result = *first; 221 | ++result; 222 | ++first; 223 | } 224 | 225 | return result; 226 | 227 | } 228 | 229 | template 230 | OutputIterator _copy(InputIterator first, InputIterator last, OutputIterator result, T*){ 231 | 232 | typedef typename _type_traits::is_POD_type is_pod; 233 | return __copy(first, last, result, is_pod()); 234 | 235 | } 236 | 237 | template 238 | OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result){ 239 | 240 | return _copy(first, last, result, value_type(first)); 241 | 242 | } 243 | 244 | template 245 | OutputIterator copy_backward(InputIterator first, InputIterator last, OutputIterator result){ 246 | 247 | OutputIterator new_result = result - (last - first); 248 | return _copy(first, last, new_result, value_type(first)); 249 | 250 | } 251 | 252 | template<> 253 | inline char *copy(char *first, char *last, char *result){ 254 | 255 | auto dist = last - first; 256 | memcpy(result, first, sizeof(*first) * dist); 257 | return result + dist; 258 | 259 | } 260 | 261 | template<> 262 | inline wchar_t *copy(wchar_t *first, wchar_t *last, wchar_t *result){ 263 | 264 | auto dist = last - first; 265 | memcpy(result, first, sizeof(*first) * dist); 266 | return result + dist; 267 | 268 | } 269 | template 270 | T1 max(T1 a, T2 b) { 271 | return a > b ? a : b; 272 | } 273 | 274 | template 275 | T1 min(T1 a, T2 b) { 276 | return a < b ? a : b; 277 | } 278 | 279 | //********** [find] ************************* 280 | //********* [Algorithm Complexity: O(N)] **************** 281 | template 282 | InputIterator find(InputIterator first, InputIterator last, const T& val){ 283 | for (; first != last; ++first){ 284 | if (*first == val) 285 | break; 286 | } 287 | return first; 288 | } 289 | } 290 | 291 | #endif -------------------------------------------------------------------------------- /alloc.cpp: -------------------------------------------------------------------------------- 1 | #include "alloc.h" 2 | 3 | namespace EasySTL { 4 | char *alloc::start_free = 0; 5 | char *alloc::end_free = 0; 6 | size_t alloc::heap_size = 0; 7 | 8 | alloc::obj * volatile alloc::free_list[alloc::_NFREELIST] = { 9 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 | }; 11 | 12 | void *alloc::allocate(size_t bytes) { 13 | if (bytes > _MAX_BYTES) { 14 | return malloc(bytes); 15 | } 16 | 17 | //选择freelist编号 18 | size_t index = FREELIST_INDEX(bytes); 19 | 20 | obj * my_list = free_list[index]; 21 | 22 | if (my_list == 0) { 23 | //没有可用的freelist,准备重新填充freelist 24 | void *r = refill(ROUND_UP(bytes)); 25 | return r; 26 | } 27 | //调整freelist,将list后面的空间前移,返回list所指的空间 28 | free_list[index] = my_list->free_list_next; 29 | return my_list; 30 | } 31 | 32 | void alloc::deallocate(void *ptr, size_t bytes) { 33 | if (bytes > _MAX_BYTES) { 34 | free(ptr); 35 | return; 36 | } 37 | 38 | size_t index = FREELIST_INDEX(bytes); 39 | obj* node = static_cast(ptr); 40 | node->free_list_next = free_list[index]; 41 | free_list[index] = node; 42 | } 43 | 44 | //重新分配内存空间 45 | void *alloc::reallocate(void *ptr, size_t old_sz, size_t new_sz) { 46 | deallocate(ptr, old_sz); 47 | ptr = allocate(new_sz); 48 | 49 | return ptr; 50 | } 51 | 52 | //返回一个大小为n的对象,并且有时候会为适当的freelist增加节点 53 | //假设bytes已经上调为8的倍数 54 | void *alloc::refill(size_t bytes) { 55 | //记录获取的区块数量 56 | size_t nobjs = _NOBJS; 57 | 58 | //从内存池中取nobjs个区块作为freelist的新节点 59 | char *chunk = chunk_alloc(bytes, nobjs); 60 | obj * volatile *my_list = 0; 61 | obj *result = 0; 62 | obj *current_obj = 0, *next_obj = 0; 63 | 64 | if (nobjs == 1) { 65 | //只获取了一个区块 66 | return chunk; 67 | } 68 | 69 | my_list = free_list + FREELIST_INDEX(bytes); 70 | 71 | result = (obj *)(chunk); 72 | 73 | //剩下的空间分离出来 74 | *my_list = next_obj = (obj *)(chunk + bytes); 75 | 76 | for (int i = 1;; ++i) { 77 | current_obj = next_obj; 78 | next_obj = (obj *)((char *)next_obj +bytes); 79 | if (nobjs - 1 == i) { 80 | current_obj->free_list_next = 0; 81 | break; 82 | } 83 | 84 | current_obj->free_list_next = next_obj; 85 | } 86 | 87 | return result; 88 | } 89 | 90 | //内存池(一大块空闲的空间) bytes已经上调为8的倍数 91 | char *alloc::chunk_alloc(size_t bytes, size_t& nobjs) { 92 | char *result = 0; 93 | size_t bytes_need = bytes * nobjs; 94 | size_t bytes_left = end_free - start_free; 95 | 96 | if (bytes_left > bytes_need) { 97 | result = start_free; 98 | start_free = start_free + bytes_need; 99 | return result; 100 | } else if (bytes_left >= bytes){ //只能提供小于nobjs个区间的内存 101 | nobjs = bytes_left / bytes; 102 | bytes_need = nobjs * bytes; 103 | result = start_free; 104 | start_free = start_free + bytes_need; 105 | return result; 106 | } else { //一个区块的无法提供 107 | //每次申请两倍的新内存+ 108 | size_t bytes_to_get = 2 * bytes_need + ROUND_UP(heap_size >> 4); 109 | //试着让内存池中的残余零头还有利用价值 110 | if (bytes_left > 0) { 111 | obj * volatile * my_list = free_list + FREELIST_INDEX(bytes_left); 112 | ((obj *)start_free)->free_list_next = *my_list; 113 | *my_list = (obj *)start_free; 114 | } 115 | 116 | start_free = (char *)malloc(bytes_to_get); 117 | if (0 == start_free) {//heap内存不足 118 | obj * volatile * my_list = 0, *p = 0; 119 | /* 120 | * 在freelist上寻找未使用的大区块。 121 | */ 122 | 123 | for (int i = 0; i <= _MAX_BYTES; i += _ALIGN) { 124 | my_list = free_list + FREELIST_INDEX(i); 125 | p = *my_list; 126 | if (0 != p) { 127 | *my_list = p->free_list_next; 128 | start_free = (char *)p; 129 | end_free = start_free + i; 130 | return chunk_alloc(bytes, nobjs); 131 | } 132 | } 133 | end_free = 0; //没有内存可用 134 | } 135 | 136 | heap_size += bytes_to_get; 137 | end_free = start_free + bytes_to_get; 138 | return chunk_alloc(bytes, nobjs); 139 | } 140 | } 141 | } -------------------------------------------------------------------------------- /alloc.h: -------------------------------------------------------------------------------- 1 | #ifndef _ALLOC_H_ 2 | #define _ALLOC_H_ 3 | /* 4 | * 简单的空间配置器 5 | */ 6 | 7 | #include 8 | 9 | namespace EasySTL { 10 | /* 11 | * 空间配置器 12 | */ 13 | class alloc { 14 | private: 15 | enum {_ALIGN = 8}; //小型区块的上调边界 16 | enum {_MAX_BYTES = 128}; //小型区块的上限 17 | enum {_NFREELIST = _MAX_BYTES / _ALIGN}; //freelist的个数 18 | enum {_NOBJS = 20};//每次增加的节点数量 19 | 20 | union obj { //free list 节点 21 | union obj* free_list_next; 22 | char client[1]; 23 | }; 24 | 25 | static obj * volatile free_list[_NFREELIST]; 26 | 27 | static char *start_free; //内存池起始地址 28 | static char *end_free; //内存池结束地址 29 | static size_t heap_size; 30 | 31 | //根据需要的区块大小,选择freelist编号 32 | static size_t FREELIST_INDEX(size_t bytes) { 33 | return ((bytes + _ALIGN - 1) / _ALIGN - 1); 34 | } 35 | 36 | //将bytes 上调至8的倍数 37 | static size_t ROUND_UP(size_t bytes) { 38 | return ((bytes + _ALIGN - 1) & ~(_ALIGN - 1)); 39 | } 40 | 41 | //返回一个大小为n的对象,并可能加入大小为n的其他区块到free-list 42 | static void *refill(size_t bytes); 43 | 44 | //配置一大块空间,可容纳_NOBJS个大小为size的区块 45 | static char *chunk_alloc(size_t bytes, size_t& nobjs); 46 | 47 | public: 48 | static void *allocate(size_t bytes); 49 | 50 | static void deallocate(void *ptr, size_t bytes); 51 | 52 | static void *reallocate(void *ptr, size_t old_sz, size_t new_sz); 53 | }; 54 | 55 | } //end of namespace EasySTL 56 | 57 | #endif -------------------------------------------------------------------------------- /allocator.h: -------------------------------------------------------------------------------- 1 | #ifndef _ALLOCATOR_H_ 2 | #define _ALLOCATOR_H_ 3 | 4 | /* 5 | * 为alloc类封装接口 6 | */ 7 | #include "alloc.h" 8 | #include "construct.h" 9 | 10 | #include 11 | #include 12 | 13 | namespace EasySTL { 14 | template 15 | class simple_alloc { 16 | public: 17 | static T *allocate(size_t n) 18 | { return 0 == n ? 0 : (T*) Alloc::allocate(n * sizeof(T));} 19 | 20 | static T *allocate(void) 21 | { return (T*) Alloc::allocate( sizeof(T) );} 22 | 23 | static void deallocate(T *p, size_t n) 24 | { if(0 != n) Alloc::deallocate(p, n * sizeof(T));} 25 | 26 | static void deallocate(T *p) 27 | { Alloc::deallocate(p, sizeof (T));} 28 | }; 29 | } 30 | 31 | #endif -------------------------------------------------------------------------------- /construct.h: -------------------------------------------------------------------------------- 1 | #ifndef _CONSTRUCT_H_ 2 | #define _CONSTRUCT_H_ 3 | 4 | #include 5 | 6 | #include "typetraits.h" 7 | 8 | namespace EasySTL { 9 | template 10 | inline void construct(T1 *ptr1, const T2& value) { 11 | new(ptr1) T1(value); //placement new 在已获取的内存上创建对象 12 | } 13 | 14 | template 15 | inline void destroy(T *ptr) { 16 | ptr->~T(); 17 | } 18 | 19 | template 20 | inline void _destory(ForwardIterator first, ForwardIterator last, _true_type) {} 21 | 22 | template 23 | inline void _destory(ForwardIterator first, ForwardIterator last, _false_type) { 24 | for (; first != last; ++first) { 25 | destroy(&*first); 26 | } 27 | } 28 | 29 | template 30 | inline void destroy(ForwardIterator first, ForwardIterator last) { 31 | typedef typename _type_traits::is_POD_type is_POD; 32 | _destory(first, last, is_POD()); 33 | } 34 | 35 | //针对char* wchar_t*的特化版本 36 | inline void destroy(char*, char*) {} 37 | inline void destroy(wchar_t*, wchar_t*) {} 38 | } 39 | 40 | #endif -------------------------------------------------------------------------------- /deque.h: -------------------------------------------------------------------------------- 1 | #ifndef _DEQUE_H_ 2 | #define _DEQUE_H_ 3 | 4 | #include "dequeIterator.h" 5 | #include "allocator.h" 6 | #include "construct.h" 7 | #include "algorithm.h" 8 | enum {_min_map_num = 8}; 9 | namespace EasySTL { 10 | template 11 | class deque{ 12 | public: 13 | typedef T value_type; 14 | typedef value_type* pointer; 15 | typedef value_type& reference; 16 | typedef size_t size_type; 17 | typedef ptrdiff_t difference_type; 18 | 19 | public: 20 | typedef _deque_iterator iterator; 21 | 22 | protected: 23 | //指向map空间上的指针类型 24 | typedef pointer *map_pointer; 25 | protected: 26 | //配置一个元素大小,value 27 | typedef simple_alloc data_allocator; 28 | //配置一个指针大小,map 29 | typedef simple_alloc map_allocator; 30 | 31 | pointer allocate_node() { 32 | return data_allocator::allocate(buffer_size()); 33 | } 34 | 35 | static size_t buffer_size() {return _deque_buf_size(BufSize, sizeof(T));} 36 | 37 | static size_t _deque_buf_size(size_t n, size_t sz) { 38 | return n != 0 ? n : (sz < 512 ? size_t(512 / sz) : size_t(1)); 39 | } 40 | 41 | int initial_map_size() { 42 | return _min_map_num; 43 | } 44 | 45 | void fill_initialize(size_type n, const value_type& value); 46 | 47 | void push_back_aux(const value_type& t); 48 | 49 | void push_front_aux(const value_type& t); 50 | 51 | void create_map_and_nodes(size_type num_elements); 52 | 53 | void reserve_map_at_back(size_type node_to_add = 1); 54 | void reserve_map_at_front(size_type node_to_add = 1); 55 | void reallocate_map(size_type node_to_add, bool add_at_front); 56 | void pop_back_aux(); //finish.cur == finish.first 释放该缓冲区 57 | void pop_front_aux(); 58 | 59 | public: 60 | deque() :start(), finish(), map_size(0), map(0){ 61 | create_map_and_nodes(0); 62 | } 63 | deque(int n, const value_type& value) 64 | : start(), finish(), map(0), map_size(0) { 65 | fill_initialize(n, value); 66 | } 67 | 68 | ~deque(){ 69 | 70 | } 71 | void push_back(const value_type& t) { 72 | if(finish.cur != finish.last - 1) { 73 | construct(finish.cur, t); 74 | ++finish.cur; 75 | } else { //需要配置新的缓冲区 76 | push_back_aux(t); 77 | } 78 | } 79 | 80 | void push_front(const value_type& t){ 81 | if (start.cur != start.first) { 82 | construct(start.cur - 1, t); 83 | --start.cur; 84 | } else {//第一缓冲区已经没有备用空间了 85 | push_front_aux(t); 86 | } 87 | } 88 | 89 | void pop_back() { 90 | if (finish.cur != finish.first) { 91 | --finish.cur; 92 | destroy(finish.cur); 93 | } else { 94 | pop_back_aux(); 95 | } 96 | } 97 | 98 | void clear(); 99 | 100 | protected: 101 | iterator start; 102 | iterator finish; 103 | 104 | //data member 105 | map_pointer map; //map首地址 106 | size_type map_size; //map存储的大小 107 | 108 | public: 109 | iterator begin() { return start;} 110 | iterator end() {return finish;} 111 | reference operator[] (size_type n) { 112 | return *(start + n); 113 | } 114 | 115 | reference front() {return *start;} 116 | reference back() { 117 | return *(finish - 1); 118 | } 119 | 120 | size_type size() const { return finish - start;} 121 | 122 | size_type max_size() const { return size_type(-1);} 123 | bool empty() const { return finish == start;} 124 | }; 125 | } 126 | #include "impl/deque.impl.h" 127 | #endif -------------------------------------------------------------------------------- /dequeIterator.h: -------------------------------------------------------------------------------- 1 | #include "iterator.h" 2 | namespace EasySTL { 3 | template 4 | struct _deque_iterator { 5 | typedef _deque_iterator iterator; 6 | typedef _deque_iterator const_iterator; 7 | 8 | //获取单个缓冲区大小 9 | static size_t buffer_size() {return _deque_buf_size(BufSize, sizeof(T));} 10 | 11 | //没有继承std的iterator,所以必须自己指明五个必要的迭代器相应型别 12 | typedef random_access_iterator_tag iterator_category; // 1 13 | typedef T value_type; // 2 14 | typedef Ptr pointer; // 3 15 | typedef Ref reference; // 4 16 | typedef size_t size_type; // 5 17 | typedef ptrdiff_t difference_type; 18 | typedef T** map_pointer; 19 | 20 | typedef _deque_iterator self; 21 | 22 | //与容器保持连接 23 | T* cur; //迭代器所指向缓冲区现行元素 24 | T* first; //迭代器所指的缓冲区的头 25 | T* last; //迭代器所指的缓冲区的尾 26 | map_pointer node; //控制中心 27 | 28 | static size_t _deque_buf_size(size_t n, size_t sz) { 29 | return n != 0 ? n : (sz < 512 ? size_t(512 / sz) : size_t(1)); 30 | } 31 | //将该迭代器指向新的缓冲区的第一个位置 32 | void set_node(map_pointer new_node) { 33 | node = new_node; 34 | first = *new_node; 35 | last = first + difference_type(buffer_size()); 36 | } 37 | 38 | reference operator*() const {return *cur; } 39 | pointer operator->() const {return &(operator*());} 40 | difference_type operator-(const self& x) const { 41 | return difference_type(buffer_size()) * (node - x.node - 1) + 42 | (cur - first) + (x.last - x.cur); 43 | } 44 | 45 | self& operator++() { //前置写法 46 | ++cur; 47 | if(cur == last) { 48 | set_node(node + 1); 49 | cur = first; 50 | } 51 | return *this; 52 | } 53 | 54 | self& operator++(int) { //后置写法 55 | self tmp = *this; 56 | ++*this; 57 | return tmp; 58 | } 59 | 60 | self& operator--() { 61 | if(cur == first) { 62 | set_node(node - 1); 63 | cur = last; 64 | } 65 | cur--; 66 | return *this; 67 | } 68 | 69 | self& operator--(int) { 70 | self tmp = *this; 71 | --*this; 72 | return tmp; 73 | } 74 | 75 | //随机存储。迭代器可以直接跳跃n的距离 76 | self& operator+=(difference_type n) { 77 | difference_type diff = n + cur - first; 78 | if(diff < (difference_type)buffer_size() && diff > 0) { 79 | cur += n; 80 | return *this; 81 | } 82 | 83 | if (diff > 0) { 84 | difference_type left = n - (last - cur); 85 | difference_type node_diff = left / (difference_type)buffer_size(); 86 | set_node(node + node_diff); 87 | cur = left % (difference_type)buffer_size(); 88 | return *this; 89 | } 90 | 91 | if (diff < 0) { 92 | difference_type left = n - (cur - first); 93 | difference_type node_diff = left / (difference_type)buffer_size(); 94 | set_node(node - node_diff); 95 | cur = last - (left % (difference_type)buffer_size()); 96 | return *this; 97 | } 98 | } 99 | 100 | self operator+(difference_type n) const { 101 | self tmp = *this; 102 | return tmp += n; 103 | } 104 | 105 | self& operator-=(difference_type n) { return *this += -n;} 106 | 107 | self operator-(difference_type n) const { 108 | self tmp = *this; 109 | return tmp -= n; 110 | } 111 | 112 | //reference operator[](difference_type n) const { return *(*this + n);} 113 | bool operator==(const self& x) const {return cur == x.cur;} 114 | bool operator!=(const self& x) const {return cur != x.cur;} 115 | bool operator<(const self& x) const { 116 | return (node == x.node) ? (cur < x.cur) : (node < x.node); 117 | } 118 | 119 | }; 120 | } -------------------------------------------------------------------------------- /error/error0116.txt: -------------------------------------------------------------------------------- 1 | Access not within mapped region at address 0xFFE801FF8 2 | Stack overflow in thread #1: can't grow stack to 0xffe801000 3 | at 0x406EA5: EasySTL::__rb_tree_iterator::__rb_tree_iterator(EasySTL::__rb_tree_iterator const&) (RBtreeIterator.h:87) 4 | 5 | 因为我递归死循环了,问题出在 6 | bool operator==(iterator iter) { return *this == iter;} 7 | 8 | 应该改为检查iterator指向的底层node是否是同一个 9 | bool operator==(const self& iter) const { return node == iter.node;} -------------------------------------------------------------------------------- /error/error0117.txt: -------------------------------------------------------------------------------- 1 | redefinition of default argument for ‘class Alloc’ 头文件没有加#ifndef 2 | 3 | cannot convert ‘std::__iterator_category >((*(const EasySTL::__rb_tree_iterator*)(& __first)))’ (type ‘std::__iterator_traits, true>::iterator_category {aka EasySTL::bidirectional_iterator_tag}’) to type ‘std::input_iterator_tag’ 4 | std::__iterator_category(__first)); -------------------------------------------------------------------------------- /error/error0118.txt: -------------------------------------------------------------------------------- 1 | could not convert ‘EasySTL::rb_tree::insert_unique(const value_type&) [with Key = std::basic_string; Value = EasySTL::pair, int>; KeyOfValue = EasySTL::select1st, int> >; Compare = EasySTL::less >; Alloc = EasySTL::alloc; EasySTL::rb_tree::value_type = EasySTL::pair, int>]((* & x))’ 2 | 3 | from ‘std::pair, int>, EasySTL::pair, int>&, EasySTL::pair, int>*>, bool>’ 4 | 5 | to ‘EasySTL::pair, int>, EasySTL::pair, int>&, EasySTL::pair, int>*>, bool>’ -------------------------------------------------------------------------------- /error/error0709-2.txt: -------------------------------------------------------------------------------- 1 | error: 2 | call of overloaded 'copy(std::basic_string*&, std::basic_string*&, std::basic_string*&)' 3 | is ambiguous 4 | copy(end_earse, finish_, start_earse); 5 | 6 | answer: 7 | 自己写的alogrithm copy函数与std中的copy函数发生冲突,编译器不知道选择哪个版本 8 | 为copy添加EasySTL::前缀 9 | -------------------------------------------------------------------------------- /error/error0709.txt: -------------------------------------------------------------------------------- 1 | error1: 2 | passing 'const EasySTL::vector, EasySTL::alloc>' as 'this' 3 | argument of 'T* EasySTL::vector::end() 4 | [with 5 | T = std::basic_string; 6 | Alloc = EasySTL::alloc; 7 | EasySTL::vector::iterator = std::basic_string*]' 8 | discards qualifiers [-fpermissive] 9 | size_type size() const { return size_type(end() - begin());} 10 | 11 | 12 | answer: 13 | const对象只能调用const成员函数;在一个加了const限定符的成员函数中,不能够调用 非const成员函数。 14 | 因为如果调用了非const成员函数,就违反了const成员函数不改变对象的规定。 15 | 所以为begin() end() 函数添加const -------------------------------------------------------------------------------- /error/error0814.txt: -------------------------------------------------------------------------------- 1 | error2: 2 | redeclaration of may not have default arguments 3 | 4 | answer: 5 | put the default argument on the declaration, not the definition. -------------------------------------------------------------------------------- /functional.h: -------------------------------------------------------------------------------- 1 | #ifndef FUNCTIONAL_H_ 2 | #define FUNCTIONAL_H_ 3 | #include "pair.h" 4 | namespace EasySTL { 5 | template 6 | struct unary_function { 7 | typedef Arg argumant_type; 8 | typedef Result result_type; 9 | }; 10 | 11 | template 12 | struct binary_function { 13 | typedef Arg1 first_argument_type; 14 | typedef Arg2 second_argument_type; 15 | typedef Result result_type; 16 | }; 17 | 18 | 19 | template 20 | struct identity : public unary_function { 21 | const T& operator()(const T& x) const {return x;} //函数调用操作符 22 | }; 23 | 24 | template 25 | struct less : public binary_function { 26 | bool operator()(const T& x, const T& y) const { return x < y;} 27 | }; 28 | 29 | // template 30 | // bool less(const T& x, const T& y) const { 31 | // return x < y; 32 | // } 33 | 34 | template 35 | struct select1st : public unary_function { 36 | const typename T::first_type& operator()(const T& x) const {return x.first;} 37 | }; 38 | } 39 | #endif -------------------------------------------------------------------------------- /impl/deque.impl.h: -------------------------------------------------------------------------------- 1 | #ifndef _DEQUE_IMP_H_ 2 | #define _DEQUE_IMP_H_ 3 | #include "../uninitialized.h" 4 | 5 | namespace EasySTL { 6 | template 7 | void deque::fill_initialize(size_type n, 8 | const value_type& value) { 9 | create_map_and_nodes(n); //安排好deque的结构,获取内存 10 | map_pointer cur; 11 | for (cur = start.node; cur < finish.node; ++cur) 12 | //已经获得了内存,构造buffer的开始节点,结束节点,初始值 13 | unitialized_fill(*cur, *cur + buffer_size(), value); 14 | unitialized_fill(finish.first, finish.cur, value); 15 | } 16 | 17 | template 18 | void deque::create_map_and_nodes(size_type num_elements) { 19 | //如果刚好整除会多分配一个节点 20 | size_type num_nodes = num_elements / buffer_size() + 1; 21 | map_size = max(initial_map_size(), num_nodes + 2); 22 | map = map_allocator::allocate(map_size); 23 | 24 | map_pointer nstart = map + (map_size - num_nodes) / 2; 25 | map_pointer nfinish = nstart + num_nodes - 1; 26 | map_pointer cur; 27 | 28 | for(cur = nstart; cur <= nfinish; cur++) { 29 | *cur = allocate_node(); 30 | } 31 | start.set_node(nstart); 32 | finish.set_node(nfinish); 33 | start.cur = start.first; 34 | finish.cur = finish.first + num_elements % buffer_size(); 35 | } 36 | 37 | template 38 | void deque::push_back_aux(const value_type& t) { 39 | value_type t_copy = t; 40 | reserve_map_at_back(); //是否需要重换一个map 41 | *(finish.node + 1) = allocate_node(); //配置新的map节点 42 | 43 | construct(finish.cur, t_copy); 44 | finish.set_node(finish.node + 1); 45 | finish.cur = finish.first; 46 | } 47 | 48 | template 49 | void deque::push_front_aux(const value_type& t) { 50 | value_type t_copy = t; 51 | reserve_map_at_front(); 52 | *(start.node - 1) = allocate_node(); 53 | 54 | start.set_node(start.node - 1); 55 | start.cur = start.last - 1; 56 | construct(start.cur, t_copy); 57 | } 58 | 59 | template 60 | void deque::reserve_map_at_back(size_type node_to_add) { 61 | if (node_to_add + 1 > map_size - (finish.node - map)) { 62 | reallocate_map(node_to_add, false); 63 | } 64 | } 65 | 66 | template 67 | void deque::reserve_map_at_front(size_type node_to_add) { 68 | if (node_to_add > start.node - map) { 69 | reallocate_map(node_to_add, true); 70 | } 71 | } 72 | 73 | template 74 | void deque::reallocate_map(size_type node_to_add, 75 | bool add_at_front) { 76 | size_type old_num_nodes = finish.node - start.node + 1; 77 | size_type new_num_nodes = old_num_nodes + node_to_add; 78 | 79 | map_pointer new_nstart; 80 | if (map_size > 2 * new_num_nodes) { 81 | //偏到一边去了,把他移到正中间来 82 | new_nstart = map + (map_size - new_num_nodes) / 2 83 | + (add_at_front ? node_to_add : 0); 84 | if (new_nstart < start.node) 85 | copy(start.node, finish.node + 1, new_nstart); 86 | else 87 | copy_backward(start.node, finish.node + 1, new_nstart + old_num_nodes); 88 | } else { 89 | size_type new_map_size = map_size + max(map_size, node_to_add) + 2; 90 | map_pointer new_map = map_allocator::allocate(new_map_size); 91 | new_nstart = new_map + (new_map_size - new_num_nodes) / 2 92 | + (add_at_front ? node_to_add : 0); 93 | copy(start.node, finish.node + 1, new_nstart); 94 | map_allocator::deallocate(map, map_size); 95 | map = new_map; 96 | map_size = new_map_size; 97 | } 98 | 99 | start.set_node(new_nstart); 100 | finish.set_node(new_nstart + old_num_nodes - 1); 101 | } 102 | 103 | template 104 | void deque::pop_back_aux(){ 105 | deallocate_node(finish.first); 106 | finish.set_node(finish.node - 1); 107 | finish.cur = finish.last - 1; 108 | destroy(finish.cur); 109 | } 110 | 111 | template 112 | void deque::pop_front_aux(){ 113 | deallocate_node(start.last); 114 | start.set_node(start.node + 1); 115 | start.cur = start.first; 116 | destroy(start.cur); 117 | } 118 | 119 | template 120 | void deque::clear() { 121 | for (map_pointer node = start.node + 1; node < finish.node; ++node) { 122 | destroy(*node, *node + buffer_size()); 123 | data_allocator::deallocate(*node, buffer_size()); 124 | } 125 | 126 | if (start.node != finish.node) { 127 | destroy(start.cur, start.last); 128 | destroy(finish.first, finish.cur); 129 | data_allocator::deallocate(finish.first, buffer_size()); //保留头缓冲区 130 | } else { 131 | destroy(start.cur, finish.cur); //将缓冲区内的元素全部析构 132 | } 133 | finish = start;// 调整状态 134 | } 135 | } 136 | 137 | #endif -------------------------------------------------------------------------------- /iterator.h: -------------------------------------------------------------------------------- 1 | #ifndef _ITERATOR_H_ 2 | #define _ITERATOR_H_ 3 | #include 4 | namespace EasySTL { 5 | //五种迭代器 6 | struct input_iterator_tag{}; 7 | struct output_iterator_tag{}; 8 | struct forward_iterator_tag : public input_iterator_tag {}; 9 | struct bidirectional_iterator_tag : public forward_iterator_tag {}; 10 | struct random_access_iterator_tag : public bidirectional_iterator_tag {}; 11 | 12 | template 13 | struct input_iterator { 14 | typedef input_iterator_tag iterator_category; 15 | typedef T value_type; 16 | typedef Distance difference_type; 17 | typedef T* pointer; 18 | typedef T& reference; 19 | }; 20 | 21 | template 22 | struct output_iterator { 23 | typedef output_iterator_tag iterator_category; 24 | typedef void value_type; 25 | typedef void difference_type; 26 | typedef void pointer; 27 | typedef void reference; 28 | }; 29 | 30 | template 31 | struct forward_iterator { 32 | typedef forward_iterator_tag iterator_category; 33 | typedef T value_type; 34 | typedef Distance difference_type; 35 | typedef T* pointer; 36 | typedef T& reference; 37 | }; 38 | 39 | template 40 | struct bidirectional_iterator { 41 | typedef bidirectional_iterator_tag iterator_category; 42 | typedef T value_type; 43 | typedef Distance difference_type; 44 | typedef T* pointer; 45 | typedef T& reference; 46 | }; 47 | template 48 | struct random_access_iterator { 49 | typedef random_access_iterator_tag iterator_category; 50 | typedef T value_type; 51 | typedef Distance difference_type; 52 | typedef T* pointer; 53 | typedef T& reference; 54 | }; 55 | 56 | //为避免挂一漏百,自行开发的迭代器最好继承自以下这个std::iterator 57 | template 59 | struct iterator { 60 | typedef Category iterator_category; 61 | typedef T value_type; 62 | typedef Distance difference_type; 63 | typedef Pointer pointer; 64 | typedef Reference reference; 65 | }; 66 | 67 | //“榨汁机” traits 68 | template 69 | struct iterator_traits { 70 | typedef typename Iterator::iterator_category iterator_category; 71 | typedef typename Iterator::value_type value_type; 72 | typedef typename Iterator::difference_type difference_type; 73 | typedef typename Iterator::pointer pointer; 74 | typedef typename Iterator::reference reference; 75 | }; 76 | 77 | //针对原生指针而设计的traits偏特化 78 | template 79 | struct iterator_traits { 80 | typedef random_access_iterator_tag iterator_category; 81 | typedef T value_type; 82 | typedef ptrdiff_t difference_type; 83 | typedef T* pointer; 84 | typedef T& reference; 85 | }; 86 | 87 | //pointer to const 的特化版本 88 | template 89 | struct iterator_traits { 90 | typedef random_access_iterator_tag iterator_category; 91 | typedef T value_type; 92 | typedef ptrdiff_t difference_type; 93 | typedef const T* pointer; 94 | typedef const T& reference; 95 | }; 96 | 97 | //判断ieterator的类型 98 | template 99 | inline typename iterator_traits::iterator_category 100 | iterator_category(const Iterator& It) { 101 | typedef typename iterator_traits::iterator_category category; 102 | return category(); 103 | } 104 | 105 | //获取迭代器的value_type 106 | template 107 | inline typename iterator_traits::value_type* 108 | value_type(const Iterator& It) { 109 | return static_cast::value_type*>(0); 110 | } 111 | 112 | //获取迭代器的distance_type 113 | template 114 | inline typename iterator_traits::difference_type* 115 | difference_type(const Iterator& It){ 116 | return static_cast::difference_type*>(0); 117 | } 118 | 119 | } 120 | 121 | #endif -------------------------------------------------------------------------------- /list.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIST_H_ 2 | #define _LIST_H_ 3 | 4 | #include "listIterator.h" 5 | #include "algorithm.h" 6 | #include "construct.h" 7 | #include "allocator.h" 8 | #include 9 | 10 | namespace EasySTL { 11 | template 12 | class list { 13 | public: 14 | typedef T value_type; 15 | typedef value_type* pointer; 16 | typedef value_type& reference; 17 | 18 | typedef _list_node list_node; 19 | typedef size_t size_type; 20 | typedef ptrdiff_t difference_type; 21 | 22 | typedef list_node* link_type; 23 | typedef simple_alloc list_node_allocator; 24 | 25 | typedef _list_iterator iterator; 26 | //配置一个节点并传回 27 | link_type get_node() { 28 | return list_node_allocator::allocate(); 29 | } 30 | 31 | //释放一个节点 32 | void put_node(link_type x) { 33 | list_node_allocator::deallocate(x); 34 | } 35 | 36 | //产生一个节点,并且带有元素值 37 | link_type create_node(const T& x) { 38 | link_type newListNode = get_node(); 39 | construct(&newListNode->data, x); //所指的数据,创建 40 | return newListNode; 41 | } 42 | 43 | //销毁一个元素点 析构并释放 44 | void destroy_node(link_type d) { 45 | destroy(&d->data); 46 | put_node(d); 47 | } 48 | 49 | public: 50 | iterator begin() const {return node->next;} 51 | iterator end() const {return node;} 52 | bool empty() const {return node->next == node;} 53 | size_type size() const { 54 | size_type result = 0; 55 | result = distance(begin(), end()); 56 | return result; 57 | } 58 | 59 | reference front() {return *begin();} 60 | reference back() {return *(--end());} 61 | 62 | //构造函数 63 | list() { empty_initialize();} //产生空的链表 64 | ~list() { 65 | clear(); 66 | erase(end()); 67 | } 68 | //尾部插入节点 69 | void push_back(const T& x) { //在list尾部空元素处添加数据元素 70 | insert(end(), x); 71 | } 72 | 73 | //头部插入节点 74 | void push_front(const T& x) { 75 | insert(begin(), x); 76 | } 77 | 78 | //删除头部节点 79 | void pop_front() { 80 | erase(begin()); 81 | } 82 | 83 | //删除尾部节点 84 | void pop_back() { 85 | erase(--end()); 86 | } 87 | 88 | //清除所有list节点 89 | void clear() { 90 | iterator s = begin(); 91 | while(s != end()) { 92 | s = erase(s); 93 | } 94 | //空list的状态 95 | node->next=node; 96 | node->prev=node; 97 | } 98 | 99 | //删除所有值为x的节点 100 | void remove(const T& x) { 101 | iterator s = begin(); 102 | while(s != end()) { 103 | if(*s == x) 104 | s = erase(s); 105 | else 106 | s++; 107 | } 108 | } 109 | 110 | //移除连续并相同的元素 111 | void unique() { 112 | iterator first = begin(); 113 | iterator last = end(); 114 | if(first == end) return; //空链表 115 | iterator next = first; 116 | while(++next != last) { 117 | if (*first == *next) 118 | erase(next); 119 | else 120 | first = next; 121 | next = first; 122 | } 123 | } 124 | 125 | iterator erase(iterator position) { 126 | link_type next_node = position.node->next; 127 | link_type prev_node = position.node->prev; 128 | prev_node->next = next_node; 129 | destroy_node(position.node); 130 | return iterator(next_node); 131 | } 132 | 133 | iterator insert(iterator position, const T& x) { 134 | link_type tmp = create_node(x); 135 | tmp->next = position.node; 136 | tmp->prev = position.node->prev; 137 | position.node->prev->next = tmp; 138 | position.node->prev = tmp; 139 | return tmp; 140 | } 141 | 142 | //将[first,last)之间的元素移动到position之前 143 | void transfer(iterator position, iterator first, iterator last) { 144 | if (last == position) 145 | return; 146 | 147 | link_type last_node = last.node->prev; 148 | //将first last取下来 149 | first.node->prev->next = last.node; 150 | last.node->prev = first.node->prev; 151 | 152 | 153 | link_type prev_node = position.node->prev; 154 | prev_node->next = first.node; 155 | first.node->prev = prev_node; 156 | 157 | last_node->next = position.node; 158 | position.node->prev = last_node; 159 | } 160 | 161 | //x接合与position之前 162 | void splice(iterator position, list& x) { 163 | if(x.empty()) 164 | return; 165 | transfer(position, x.begin(), x.end()); 166 | } 167 | 168 | //将某一个位置上的元素接合到position之前 169 | void splice(iterator position, iterator i) { 170 | iterator j = i; 171 | j++; 172 | transfer(position, i, j); 173 | } 174 | 175 | // 176 | void splice(iterator position, iterator first, iterator last) { 177 | if(position == last) 178 | return; 179 | transfer(position, first, last); 180 | } 181 | 182 | //merge 将x 与*this合并,两个list必须经过递增排序 183 | void merge(list& x) { 184 | iterator p = begin(); 185 | iterator x_start = x.begin(); 186 | 187 | while(p != end() && x_start != x.end()) { 188 | std::cout<<*p< *p) 190 | p++; 191 | else { 192 | iterator next = x_start + 1; //注意:迭代器跟着节点跑,会脱离原来的list 193 | splice(p, x_start); 194 | x_start = next; 195 | } 196 | } 197 | 198 | //如果x没完就添加到尾巴上 199 | if(!x.empty()) 200 | splice(end(), x_start, x.end()); 201 | } 202 | 203 | //reverse颠倒顺序 204 | void reverse() { 205 | iterator start = begin(); 206 | iterator stop = end(); 207 | if(size() == 0 || size() == 1) 208 | return; 209 | start++; 210 | while(start != stop) { 211 | iterator next = start + 1; 212 | splice(begin(), start); 213 | start = next; 214 | } 215 | } 216 | 217 | //与x交换成员 交换完成后原来两个list上的迭代器要注意 218 | void swap(list& x) { 219 | link_type tmp = x.node; 220 | x.node = this->node; 221 | this->node = tmp; 222 | } 223 | 224 | //sort list不能使用STL的sort,应为他的迭代器是不是ramdon的 225 | //这里使用的是插入排序 226 | void sort() { 227 | if(size() == 0 || size() == 1) 228 | return; 229 | list tmp; 230 | iterator q = begin(); 231 | while(!empty()) { 232 | iterator p = tmp.begin(); 233 | while(p!= tmp.end() && *p < *q) 234 | p++; 235 | tmp.splice(p, q); 236 | q = begin(); 237 | } 238 | //将tmp赋给本list 239 | swap(tmp); 240 | } 241 | 242 | protected: 243 | link_type node; //list是一个环状双向链表,一个指针即可表示整个环状双向链表,指向尾端的空白节点 244 | 245 | void empty_initialize() { 246 | node = get_node(); 247 | node->next = node; 248 | node->prev = node; 249 | } 250 | }; 251 | } 252 | 253 | #endif -------------------------------------------------------------------------------- /listIterator.h: -------------------------------------------------------------------------------- 1 | #include "listNode.h" 2 | #include "iterator.h" 3 | namespace EasySTL { 4 | //迭代器本身不是指针,因为list不是连续的区间 5 | template 6 | struct _list_iterator { 7 | typedef _list_iterator iterator; //指向内部元素值得迭代器 8 | typedef _list_iterator self; //指向list节点的迭代器 9 | typedef bidirectional_iterator_tag iterator_category; 10 | typedef T value_type; 11 | typedef Ptr pointer; 12 | typedef Ref reference; 13 | typedef _list_node* link_type; 14 | typedef size_t size_type; 15 | typedef ptrdiff_t difference_type; 16 | 17 | link_type node; //普通指针指向节点 18 | _list_iterator(link_type x) : node(x) {} 19 | _list_iterator() {} 20 | _list_iterator(const iterator& x) : node(x.node) {} 21 | bool operator==(const self& x) const {return node == x.node;} 22 | bool operator!=(const self& x) const {return node != x.node;} 23 | 24 | //deference 25 | reference operator*() const {return (*node).data;} 26 | pointer operator->() const {return &(operator*());} //??? 27 | 28 | //迭代器向前移动一个位置(++i) 29 | self& operator++() { 30 | node = node->next; 31 | return *this; 32 | } 33 | 34 | //迭代器向前移动一个位置(i++) 35 | self operator++(int) { 36 | self tmp = *this; 37 | ++*this; 38 | return tmp; 39 | } 40 | 41 | //对迭代器递减1 (--i) 42 | self& operator--() { 43 | node = node->prev; 44 | return *this; 45 | } 46 | 47 | //对迭代器递减1 (i--) 48 | self operator--(int) { 49 | self tmp = *this; 50 | --*this; 51 | return tmp; 52 | } 53 | 54 | self operator+(int dis){ 55 | self tmp = *this; 56 | while(dis-- > 0) { 57 | tmp = tmp.node->next; 58 | } 59 | return tmp; 60 | } 61 | 62 | self operator-(int dis){ 63 | self tmp = *this; 64 | while(dis-- > 0) { 65 | tmp = tmp.node->prev; 66 | } 67 | return tmp; 68 | } 69 | }; 70 | } 71 | -------------------------------------------------------------------------------- /listNode.h: -------------------------------------------------------------------------------- 1 | template 2 | struct _list_node { //list是双向的 3 | typedef _list_node* void_pointer; 4 | void_pointer prev; 5 | void_pointer next; 6 | T data; 7 | }; 8 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "test/vectorTest.h" 2 | #include "test/listTest.h" 3 | #include "test/dequeTest.h" 4 | #include "test/heapTest.h" 5 | #include "test/rbtreeTest.h" 6 | #include "test/setTest.h" 7 | #include "test/mapTest.h" 8 | int main() { 9 | //EasySTL::ListTest::testCase1(); 10 | //EasySTL::VectorTest::testCase1(); 11 | //EasySTL::DequeTest::testCase1(); 12 | //EasySTL::RbtreeTest::testCase1(); 13 | // EasySTL::SetTest::testCase1(); 14 | EasySTL::MapTest::testCase1(); 15 | getchar(); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | stl : main.o listTest.o vectorTest.o alloc.o dequeTest.o heapTest.o rbtreeTest.o setTest.o mapTest.o 2 | g++ -g -std=c++11 -o stl main.o listTest.o vectorTest.o alloc.o dequeTest.o heapTest.o rbtreeTest.o setTest.o mapTest.o 3 | 4 | main.o : main.cpp ./test/mapTest.h 5 | g++ -g -std=c++11 -c main.cpp 6 | 7 | listTest.o : ./test/listTest.cpp ./test/listTest.h 8 | g++ -g -std=c++11 -c ./test/listTest.cpp 9 | 10 | vectorTest.o : ./test/vectorTest.cpp ./test/vectorTest.h 11 | g++ -g -std=c++11 -c ./test/vectorTest.cpp 12 | 13 | dequeTest.o : ./test/dequeTest.cpp ./test/dequeTest.h 14 | g++ -g -std=c++11 -c ./test/dequeTest.cpp 15 | 16 | heapTest.o : ./test/heapTest.cpp ./test/heapTest.h 17 | g++ -g -std=c++11 -c ./test/heapTest.cpp 18 | 19 | rbtreeTest.o : ./test/rbtreeTest.cpp ./test/rbtreeTest.h 20 | g++ -g -std=c++11 -c ./test/rbtreeTest.cpp 21 | 22 | setTest.o : ./test/setTest.cpp ./test/setTest.h 23 | g++ -g -std=c++11 -c ./test/setTest.cpp 24 | 25 | mapTest.o : ./test/mapTest.cpp ./test/mapTest.h 26 | g++ -g -std=c++11 -c ./test/mapTest.cpp 27 | 28 | alloc.o : alloc.cpp alloc.h 29 | g++ -g -std=c++11 -c alloc.cpp 30 | 31 | clean : 32 | rm stl main.o listTest.o vectorTest.o alloc.o dequeTest.o heapTest.o rbtreeTest.o setTest.o 33 | -------------------------------------------------------------------------------- /map.h: -------------------------------------------------------------------------------- 1 | /*** 2 | * 所有元素会根据元素的键值自动被排序,map的所有元素都是pair,同时拥有实值和键值。pair的第一元素被视为键值 3 | * 第二元素被视为实值。map不允许两个元素拥有相同的键值。 4 | * map 不允许修改键值,但允许修改实值 5 | */ 6 | #ifndef MAP_H_ 7 | #define MAP_H_ 8 | 9 | #include "pair.h" 10 | #include "functional.h" 11 | #include "allocator.h" 12 | #include "rbtree.h" 13 | namespace EasySTL { 14 | template , 16 | class Alloc = alloc> 17 | class map { 18 | public: 19 | typedef Key key_type; 20 | typedef T data_type; 21 | typedef T mapped_type; 22 | typedef pair value_type; 23 | typedef Compare key_compare; // 键值比较函数,创建对象,可以直接使用() 24 | 25 | 26 | //内部类 27 | //two arguments and one return value 28 | class value_compare 29 | : public binary_function { 30 | friend class map; 31 | protected: 32 | Compare comp; 33 | value_compare(Compare c) :comp(c) {} 34 | public: 35 | bool operator()(const value_type& x, const value_type& y) const { 36 | return comp(x.first, y.first); 37 | } 38 | }; 39 | private: 40 | //以下定义表述型别。以map元素型别(一个pair)的第一型别,作为RB-tree节点的键值型别 41 | typedef rb_tree, key_compare, Alloc> rep_type; 43 | rep_type t; 44 | public: 45 | typedef typename rep_type::pointer pointer; 46 | typedef typename rep_type::const_pointer const_pointer; 47 | typedef typename rep_type::reference reference; 48 | typedef typename rep_type::const_reference const_reference; 49 | typedef typename rep_type::iterator iterator; //允许修改 50 | 51 | typedef typename rep_type::const_iterator const_iterator; 52 | typedef typename rep_type::size_type size_type; 53 | typedef typename rep_type::difference_type difference_type; 54 | 55 | map() : t(Compare()) {} 56 | explicit map(const Compare& comp) : t(comp) {} 57 | 58 | template 59 | map(InputIterator first, InputIterator last) 60 | : t(Compare()) { t.insert_unique(first, last);} 61 | 62 | template 63 | map(InputIterator first, InputIterator last, const Compare& comp) 64 | : t(comp) {t.insert_unique(first, last);} 65 | 66 | map(const map& x) : t(x.t) {} 67 | map& operator=(const map& x) { 68 | t = x.t; 69 | return *this; 70 | } 71 | 72 | //return 比较函数 73 | key_compare key_comp() const { return t.key_comp();} 74 | value_compare value_comp() const { return value_compare(t.key_comp());} 75 | iterator begin() { return t.begin();} 76 | const_iterator begin() const { return t.begin();} 77 | iterator end() { return t.end();} 78 | const_iterator end() const { return t.end();} 79 | bool empty() const { return t.empty();} 80 | size_type size() const { return t.size();} 81 | size_type max_size() const { return t.max_size();} 82 | //下标操作 83 | T& operator[](const key_type& k) { 84 | //insert 返回pair 85 | return (*((insert(value_type(k, T()))).first)).second; 86 | } 87 | void swap(map& x) {t.swap(x.t);} 88 | 89 | //return pair 的值 90 | pair insert(const value_type& x) { 91 | return t.insert_unique(x); 92 | } 93 | 94 | iterator insert(iterator position, const value_type& x) { 95 | return t.insert_unique(position, x); 96 | } 97 | 98 | template 99 | void insert(InputIterator first, InputIterator last) { 100 | t.insert_unique(first, last); 101 | } 102 | 103 | void erase(iterator position) {t.erase(position);} 104 | size_type erase(const key_type& x) {return t.erase(x);} 105 | void erase(iterator first, iterator last) {t.erase(first, last);} 106 | void clear() {t.clear();} 107 | 108 | iterator find(const key_type& x) { return t.find(x);} 109 | size_type count(const key_type& x) const {return t.count(x);} 110 | 111 | friend bool operator==(const map& x, 112 | const map& y) { 113 | return x.t == y.t; 114 | } 115 | }; 116 | 117 | template 118 | inline bool operator<(const map& x, 119 | const map& y) { 120 | return x.t < y.t; 121 | } 122 | } 123 | #endif -------------------------------------------------------------------------------- /mapTest.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hunterzhao/EasySTL/2a876f94438b2a3d6b600a12ac86dc339cf2cd45/mapTest.o -------------------------------------------------------------------------------- /pair.h: -------------------------------------------------------------------------------- 1 | #ifndef PAIR_H_ 2 | #define PAIR_H_ 3 | namespace EasySTL { 4 | template 5 | struct pair { 6 | typedef T1 first_type; 7 | typedef T2 second_type; 8 | 9 | T1 first; 10 | T2 second; 11 | pair() : first(T1()), second(T2()) {} 12 | pair(const T1& a, const T2& b) : first(a), second(b) {} 13 | }; 14 | } 15 | #endif -------------------------------------------------------------------------------- /pic/STL文件关系树.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hunterzhao/EasySTL/2a876f94438b2a3d6b600a12ac86dc339cf2cd45/pic/STL文件关系树.png -------------------------------------------------------------------------------- /pic/STL文件关系树.xmind: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hunterzhao/EasySTL/2a876f94438b2a3d6b600a12ac86dc339cf2cd45/pic/STL文件关系树.xmind -------------------------------------------------------------------------------- /rbtree.h: -------------------------------------------------------------------------------- 1 | #ifndef RBTREE_H_ 2 | #define RBTREE_H_ 3 | #include "pair.h" 4 | #include "RBtreeIterator.h" 5 | #include "construct.h" 6 | #include "allocator.h" 7 | namespace EasySTL { 8 | template 10 | class rb_tree { 11 | protected: 12 | typedef void* void_pointer; 13 | typedef __rb_tree_node_base* base_ptr; 14 | typedef __rb_tree_node rb_tree_node; 15 | typedef simple_alloc rb_tree_node_allocator; 16 | public: 17 | typedef Key key_type; 18 | typedef Value value_type; 19 | typedef value_type* pointer; 20 | typedef const value_type* const_pointer; 21 | typedef const value_type& const_reference; 22 | 23 | typedef rb_tree_node* link_type; 24 | typedef size_t size_type; 25 | typedef ptrdiff_t difference_type; 26 | 27 | typedef __rb_tree_color_type color_type; 28 | typedef value_type& reference; 29 | 30 | protected: 31 | link_type get_node() {return rb_tree_node_allocator::allocate();} 32 | void put_node(link_type p) {rb_tree_node_allocator::deallocate(p);} 33 | void destroy(Value* value_field) {} 34 | link_type create_node(const value_type& x) { 35 | link_type tmp = get_node(); //配置空间 36 | construct(&tmp->value_field, x); //构造内容 37 | return tmp; 38 | } 39 | 40 | link_type clone_node(link_type x) { //赋值一个node 41 | link_type tmp = create_node(x->value_field); 42 | tmp->color = x->color; 43 | tmp->left = 0; 44 | tmp->right= 0; 45 | return tmp; 46 | } 47 | 48 | void destroy_node(link_type p) { 49 | destroy(&p->value_field); //析构内容,将 value_field 的地址传给该函数 50 | put_node(p); //释放内存 51 | } 52 | 53 | void clear() { 54 | 55 | } 56 | protected: 57 | //rbtree 只以三笔数据表现 58 | size_type node_count; //树上的节点个数 59 | link_type header; //实现上的a trick,与root互为父节点,header的左右孩子都是root 60 | Compare key_compare; //传入的节点键值大小比较准则 61 | 62 | //方便获取header的成员 63 | link_type& root() const {return (link_type&) header->parent;} 64 | link_type& leftmost() const {return (link_type&) header->left;} 65 | link_type& rightmost() const {return (link_type&) header->right;} 66 | 67 | //以下6个函数用来方便取得节点x的成员 68 | static link_type& left(link_type x) 69 | { return (link_type&)(x->left);} 70 | 71 | static link_type& right(link_type x) 72 | { return (link_type&)(x->right);} 73 | 74 | static link_type& parent(link_type x) 75 | { return (link_type&)(x->parent);} 76 | 77 | static reference value(link_type x) 78 | { return x->value_field;} 79 | 80 | static const Key& key(link_type x) 81 | { return KeyOfValue() (value(x));} 82 | 83 | static color_type& color(link_type x) 84 | { return (color_type&) (x->color);} 85 | 86 | //以下6个函数用来方便取得x的成员 87 | static link_type& left(base_ptr x) 88 | { return (link_type&)(x->left);} 89 | 90 | static link_type& right(base_ptr x) 91 | { return (link_type&)(x->right);} 92 | 93 | static link_type& parent(base_ptr x) 94 | { return (link_type&)(x->parent);} 95 | 96 | static reference value(base_ptr x) 97 | { return ((link_type)x)->value_field;} 98 | 99 | static const Key& key(base_ptr x) 100 | { return KeyOfValue() (value(link_type(x)));} 101 | 102 | static color_type& color(base_ptr x) 103 | { return (color_type&) (link_type(x)->color);} 104 | 105 | static link_type minimum (link_type x) { 106 | return (link_type) __rb_tree_node_base::minimum(x); 107 | } 108 | 109 | static link_type maximum(link_type x) { 110 | return (link_type) __rb_tree_node_base::maximum(x); 111 | } 112 | public: 113 | typedef __rb_tree_iterator iterator; 114 | typedef __rb_tree_iterator const_iterator; 115 | 116 | private: 117 | //新值插入点 插入点的父节点 新值 118 | iterator __insert(base_ptr x_, base_ptr y_, const Value& v) { 119 | link_type x = (link_type) x_; 120 | link_type y = (link_type) y_; 121 | link_type z; 122 | if (y==header || x != 0 || key_compare(KeyOfValue()(v), key(y))) { 123 | z = create_node(v); 124 | left(y) = z; //这使得y即为header时,leftmost() = z 125 | if(y==header) { 126 | root() = z; 127 | rightmost() = z; 128 | } else if (y == leftmost()) //y 为最左节点 129 | leftmost() =z; 130 | } else { 131 | z = create_node(v); 132 | right(y) = z; 133 | if(y==rightmost()) rightmost() = z; 134 | } 135 | parent(z) = y; 136 | left(z) = 0; 137 | right(z) = 0; 138 | 139 | __rb_tree_rebalance(z, header->parent); 140 | ++node_count; 141 | return iterator(z); 142 | } 143 | 144 | link_type __copy(link_type x, link_type p); 145 | void __erase(link_type x); 146 | void init() { 147 | header = get_node(); //产生一个节点空间,令header指向它 148 | color(header) = __rb_tree_red; //header为红色,区分header与root 149 | 150 | root() = 0; 151 | leftmost() = header; //令header的左子节点为自己 152 | rightmost()= header; //令header的右节点为自己 153 | } 154 | 155 | public: 156 | rb_tree(const Compare& comp = Compare()) 157 | : node_count(0), key_compare(comp) { init();} 158 | 159 | ~rb_tree() { 160 | clear(); 161 | put_node(header); 162 | } 163 | rb_tree& 164 | operator=(const rb_tree& x); 165 | 166 | public: 167 | Compare key_comp() const {return key_compare;} 168 | iterator begin() const {return leftmost();} 169 | iterator end() const {return header;} //RBtree的重点为header所指的位置 170 | bool empty() const { return node_count == 0;} 171 | size_type size() const {return node_count;} 172 | size_type max_size() const { return size_type(-1);} 173 | 174 | public: 175 | //将想插入REtree中节点独一无二 如果插入失败返回的是指向该节点的迭代器· 176 | pair insert_unique(const value_type& v) { 177 | link_type y = header; 178 | link_type x = root(); 179 | bool comp = true; 180 | while ( x != 0) { 181 | y = x; 182 | comp = key_compare(KeyOfValue()(v), key(x)); 183 | x = comp ? left(x) : right(x); 184 | } 185 | //离开while后,y所指插入点的父节点(此时的它必为叶节点) 186 | iterator j = iterator(y); 187 | if (comp) 188 | if (j == begin()) 189 | return pair(__insert(x, y, v), true); 190 | else 191 | --j; 192 | 193 | if (key_compare(key(j.node), KeyOfValue()(v))) 194 | return pair(__insert(x, y, v), true); 195 | 196 | return pair(j, false); 197 | } 198 | 199 | template 200 | bool insert_unique(iterator first, iterator last) { 201 | for(auto it =first;it!=last;it++) { 202 | insert_unique(*it); 203 | } 204 | } 205 | //将想插入RB-tree中允许节点值重复 206 | iterator insert_equal(const value_type& v) { 207 | link_type y = header; 208 | link_type x = root(); //从根节点开始 209 | while(x != 0) { 210 | y = x; 211 | x = key_compare(KeyOfValue()(v), key(x)) ? left(x) : right(x); 212 | } 213 | return __insert(x, y, v); 214 | } 215 | 216 | 217 | //重新令树形平衡(颜色 旋转树形) 218 | //参数1 为新增节点, 参数2 为root 219 | inline void __rb_tree_rebalance(__rb_tree_node_base* x, __rb_tree_node_base*& root) { 220 | x->color = __rb_tree_red; //新节点为红色 221 | while(x!=root && x->parent->color == __rb_tree_red) {//父节点为红 222 | if (x->parent == x->parent->parent->left) {//父节点为祖父节点的左节点 223 | //父节点为祖父节点之左子节点 224 | __rb_tree_node_base* y = x->parent->parent->right;//令y为伯父节点 225 | if (y && y->color == __rb_tree_red) { //伯父节点存在,且为红 226 | x->parent->color = __rb_tree_black;//更改父节点为黑 227 | y->color = __rb_tree_black; //更改伯父节点为黑 228 | x->parent->parent->color = __rb_tree_red;//更改祖父节点为红 229 | x = x->parent->parent; 230 | } else {//无伯父节点或伯父节点为黑 231 | if (x==x->parent->right) {//如果新节点为父节点之右节点 232 | x=x->parent; 233 | __rb_tree_rotate_left(x, root); //第一参数为左旋点 234 | } 235 | x->parent->color = __rb_tree_black; 236 | x->parent->parent->color = __rb_tree_red; 237 | __rb_tree_rotate_right(x->parent->parent, root); //第一参数为右旋点 238 | } 239 | } else { //父节点为祖父节点之右子节点 240 | __rb_tree_node_base* y = x->parent->parent->left;//令y为伯父节点 241 | if(y&&y->color == __rb_tree_red) { //有伯父节点,且为红色 242 | x->parent->color = __rb_tree_black;//更改父节点为黑 243 | y->color=__rb_tree_black; //更改伯父节点为黑 244 | x->parent->parent->color=__rb_tree_red;//更改祖父节点为红 245 | x=x->parent->parent; //继续往上检查 246 | } else{ //无伯父节点,或伯父节点为黑 247 | if(x==x->parent->left) { //如果新节点为父节点之左子节点 248 | x = x->parent; 249 | __rb_tree_rotate_right(x, root);//第一参数为右旋点 250 | } 251 | x->parent->color = __rb_tree_black; //改变颜色 252 | x->parent->parent->color = __rb_tree_red; 253 | __rb_tree_rotate_left(x->parent->parent, root);//第一参数为左旋点 254 | } 255 | } 256 | 257 | } //end of while 258 | root->color = __rb_tree_black; //root节点永远为黑 259 | } 260 | 261 | inline void 262 | __rb_tree_rotate_left(__rb_tree_node_base* x, 263 | __rb_tree_node_base*& root) 264 | { 265 | //x 为旋转点 266 | __rb_tree_node_base* y = x->right; 267 | x->right = y->left; 268 | if (y->left != 0) 269 | y->left->parent = x; 270 | y->parent = x->parent; 271 | 272 | if(x==root) 273 | root = y; 274 | else if (x==x->parent->left) 275 | x->parent->left = y; 276 | else 277 | x->parent->right = y; 278 | y->left = x; 279 | x->parent = y; 280 | } 281 | 282 | inline void 283 | __rb_tree_rotate_right(__rb_tree_node_base* x, 284 | __rb_tree_node_base*& root) 285 | { 286 | //x为旋转点 287 | __rb_tree_node_base* y = x->left; 288 | x->left = y->right; 289 | if(y->right != 0) 290 | y->right->parent = x; 291 | y->parent = x->parent; 292 | 293 | //令y完全顶替x的位置(必须将其父节点的关系完全接收过来) 294 | if(x==root) 295 | root = y; 296 | else if(x==x->parent->right) 297 | x->parent->right = y; 298 | else 299 | x->parent->left = y; 300 | y->right = x; 301 | x->parent = y; 302 | } 303 | 304 | iterator find(const Key& k) { 305 | link_type y = header; //last node which is not less than k 306 | link_type x = root(); //current node 307 | 308 | while(x != 0) 309 | if (!key_compare(key(x), k)) //该数是否比 k 大,是的话向左子树去 310 | y = x, x = left(x); //注意语法! 311 | else 312 | x = right(x); 313 | iterator j = iterator(y); 314 | return (j==end() || key_compare(k, key(j.node))) ? end() : j; 315 | } 316 | 317 | }; 318 | } 319 | #endif -------------------------------------------------------------------------------- /set.h: -------------------------------------------------------------------------------- 1 | #ifndef SET_H_ 2 | #define SET_H_ 3 | 4 | #include "rbtree.h" 5 | #include "functional.h" 6 | #include "iterator.h" 7 | #include "pair.h" 8 | namespace EasySTL { 9 | 10 | template , class Alloc = alloc> 11 | class set { 12 | public: 13 | typedef Key key_type; 14 | typedef Key value_type; 15 | // key_compare 和 value_compare 使用同一个比较函数 16 | typedef Compare key_compare; 17 | typedef Compare value_compare; 18 | 19 | private: 20 | typedef rb_tree, key_compare, Alloc> rep_type; 22 | rep_type t; //采用红黑树来表现set 23 | public: 24 | typedef typename rep_type::const_pointer pointer; 25 | typedef typename rep_type::const_pointer const_pointer; 26 | typedef typename rep_type::const_reference reference; 27 | typedef typename rep_type::const_reference const_reference; 28 | typedef typename rep_type::const_iterator iterator; 29 | //set 的迭代器无法执行写入操作 30 | typedef typename rep_type::const_iterator const_iterator; 31 | //typedef typename rep_type::const_reverse_iterator reverse_iterator; 32 | //typedef typename rep_type::const_reverse_iterator const_reverse_iterator; 33 | typedef typename rep_type::size_type size_type; 34 | typedef typename rep_type::difference_type difference_type; 35 | 36 | set() : t(Compare()) {} 37 | explicit set(const Compare& comp) : t(comp) {} 38 | 39 | template 40 | set(InputIterator first, InputIterator last) 41 | : t(Compare()) {t.insert_unique(first, last);} 42 | 43 | template 44 | set(InputIterator first, InputIterator last, const Compare& comp) 45 | : t(comp) {t.insert_unique(first, last);} 46 | 47 | set(const set& x) : t(x.t) {} 48 | set& operator=(const set& x) 49 | { t = x.t; return *this;} 50 | 51 | //accessors: 52 | key_compare key_comp() const { return t.key_comp();} 53 | value_compare value_comp() const { return t.key_comp();} 54 | iterator begin() const {return t.begin();} 55 | iterator end() const {return t.end();} 56 | //reverse_iterator rbegin() const {return t.rbegin();} 57 | //reverse_iterator rend() const {return t.rend();} 58 | bool empty() const {return t.empty();} 59 | size_type size() const {return t.size();} 60 | size_type max_size() const {return t.max_size();} 61 | void swap(set& x) {t.swap(x.t);} 62 | 63 | typedef pair pair_iterator_bool; 64 | pair_iterator_bool insert(const value_type& x) { 65 | pair p = t.insert_unique(x); 66 | return pair(p.first, p.second); 67 | } 68 | 69 | iterator insert(iterator position, const value_type& x){ 70 | typedef typename rep_type::iterator rep_iterator; 71 | return t.insert_unique((rep_iterator&)position, x); 72 | } 73 | 74 | template 75 | void insert(InputIterator first, InputIterator last) { 76 | t.insert(first, last); 77 | } 78 | 79 | void erase(iterator position) { 80 | typedef typename rep_type::iterator rep_iterator; 81 | t.erase((rep_iterator&)position); 82 | } 83 | size_type erase(const key_type& x) { 84 | return t.erase(x); 85 | } 86 | void erase(iterator first, iterator last) { 87 | typedef typename rep_type::iterator rep_iterator; 88 | t.erase((rep_iterator&)first, (rep_iterator&)last); 89 | } 90 | void clear() {t.clear();} 91 | iterator find(const key_type& x) const {return t.find(x);} 92 | size_type count(const key_type& x) const {return t.count(x);} 93 | iterator lower_bound(const key_type& x) const { 94 | return t.lower_bound(x); 95 | } 96 | iterator upper_bound(const key_type& x) const { 97 | return t.upper_bound(x); 98 | } 99 | pair equal_range(const key_type&x) const { 100 | return t.equal_range(x); 101 | } 102 | 103 | 104 | }; 105 | 106 | template 107 | inline bool operator==(const set& x, 108 | const set& y) { 109 | return x.t == y.t; 110 | } 111 | 112 | template 113 | inline bool operator < (const set& x, 114 | const set& y) { 115 | return x.t < y.t; 116 | } 117 | 118 | } 119 | #endif -------------------------------------------------------------------------------- /test/dequeTest.cpp: -------------------------------------------------------------------------------- 1 | #include "dequeTest.h" 2 | 3 | namespace EasySTL { 4 | namespace DequeTest { 5 | void testCase1(){ 6 | //std::string old_SGI_vector = "old_SGI_vector"; 7 | //std::string new_EasySTL_vector = "new_EasySTL_vector"; 8 | //stdVec v1(10, "zzz"); 9 | // easyList v1; 10 | // v1.push_back("abc"); 11 | // v1.push_back("def"); 12 | // v1.push_back("ghi"); 13 | // v1.push_back("def"); 14 | 15 | 16 | // stdList v2; 17 | // v2.push_back("abc"); 18 | // v2.push_back("def"); 19 | // v2.push_back("ghi"); 20 | // v2.push_back("def"); 21 | 22 | stdDeque v1; 23 | 24 | v1.push_back(2); 25 | v1.push_back(5); 26 | v1.push_back(3); 27 | v1.push_back(9); 28 | 29 | easyDeque v2; 30 | 31 | v2.push_back(2); 32 | v2.push_back(5); 33 | v2.push_back(3); 34 | v2.push_back(9); 35 | EasySTL::Test::print_container(v2,"deque"); 36 | if (EasySTL::Test::container_equal(v1, v2)){ 37 | std::cout <<"equel"< 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | namespace EasySTL { 14 | namespace DequeTest{ 15 | template 16 | using stdDeque = std::deque < T >; 17 | 18 | template 19 | using easyDeque = EasySTL::deque < T >; 20 | 21 | void testCase1(); 22 | } 23 | } 24 | #endif -------------------------------------------------------------------------------- /test/heapTest.cpp: -------------------------------------------------------------------------------- 1 | #include "heapTest.h" 2 | 3 | namespace EasySTL { 4 | namespace HeapTest { 5 | void testCase1(){ 6 | int ia[9] = {0,2,1,3,6,9,7,8,5}; 7 | stdVec vec(ia, ia+9); 8 | EasySTL::make_heap(vec.begin(), vec.end()); 9 | EasySTL::Test::print_container(vec, "make_heap"); 10 | 11 | vec.push_back(4); 12 | EasySTL::push_heap(vec.begin(), vec.end()); 13 | EasySTL::Test::print_container(vec, "push_heap"); 14 | 15 | EasySTL::pop_heap(vec.begin(), vec.end()); 16 | std::cout<< vec.back() < 5 | #include "../vector.h" 6 | #include "testFun.h" 7 | namespace EasySTL { 8 | namespace HeapTest { 9 | template 10 | using stdVec = std::vector < T >; 11 | 12 | template 13 | using easyVec = EasySTL::vector < T >; 14 | 15 | void testCase1(); 16 | } 17 | } 18 | 19 | #endif -------------------------------------------------------------------------------- /test/listTest.cpp: -------------------------------------------------------------------------------- 1 | #include "listTest.h" 2 | 3 | namespace EasySTL { 4 | namespace ListTest { 5 | void testCase1(){ 6 | //std::string old_SGI_vector = "old_SGI_vector"; 7 | //std::string new_EasySTL_vector = "new_EasySTL_vector"; 8 | //stdVec v1(10, "zzz"); 9 | // easyList v1; 10 | // v1.push_back("abc"); 11 | // v1.push_back("def"); 12 | // v1.push_back("ghi"); 13 | // v1.push_back("def"); 14 | 15 | 16 | // stdList v2; 17 | // v2.push_back("abc"); 18 | // v2.push_back("def"); 19 | // v2.push_back("ghi"); 20 | // v2.push_back("def"); 21 | 22 | easyList v1; 23 | v1.push_back(2); 24 | v1.push_back(5); 25 | v1.push_back(3); 26 | v1.push_back(9); 27 | 28 | easyList v2; 29 | v2.push_back(1); 30 | v2.push_back(1.5); 31 | v2.push_back(4); 32 | v2.push_back(7); 33 | 34 | //v1.transfer(v1.begin()+2, v2.begin(), v2.end()); 35 | //v1.reverse(); 36 | //std::cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | namespace EasySTL { 14 | namespace ListTest{ 15 | template 16 | using stdList = std::list < T >; 17 | 18 | template 19 | using easyList = EasySTL::list < T >; 20 | 21 | void testCase1(); 22 | } 23 | } 24 | #endif -------------------------------------------------------------------------------- /test/mapTest.cpp: -------------------------------------------------------------------------------- 1 | #include "mapTest.h" 2 | #include "../pair.h" 3 | #include 4 | #include 5 | 6 | namespace EasySTL { 7 | namespace MapTest { 8 | using string = std::string; 9 | void testCase1() { 10 | map simap; 11 | simap[string("jihou")] = 1; 12 | simap[string("jerry")] = 2; 13 | simap[string("jason")] = 3; 14 | 15 | const pair value(string("david"),5); 16 | simap.insert(value); 17 | 18 | auto iter = simap.begin(); 19 | for(;iter != simap.end();++iter) 20 | std::cout<first <<' ' <second< 5 | namespace EasySTL { 6 | namespace RbtreeTest { 7 | void testCase1() { 8 | 9 | rb_tree, less > itree; 10 | //std::cout< 5 | namespace EasySTL { 6 | namespace SetTest { 7 | 8 | void testCase1() { 9 | int ia[5] = {0,1,3,6,2}; 10 | set iset(ia, ia+5); 11 | std::set stdset(ia, ia+5); 12 | std::cout<< "size=" << iset.size() < 5 | #include 6 | #include 7 | 8 | namespace EasySTL { 9 | namespace Test{ 10 | template 11 | void print_container(Container& container, const std::string& name = ""){//不是每一个容器都有const_iterator 12 | std::cout << name << " :"; 13 | for (auto val : container){ 14 | std::cout << val << " "; 15 | } 16 | std::cout << std::endl; 17 | } 18 | 19 | 20 | 21 | template 22 | bool container_equal(Container1& con1, Container2& con2){//不是每一个容器都有const_iterator 23 | auto first1 = std::begin(con1), last1 = std::end(con1); 24 | auto first2 = std::begin(con2), last2 = std::end(con2); 25 | for (; first1 != last1 && first2 != last2; ++first1, ++first2){ 26 | if (*first1 != *first2) 27 | return false; 28 | } 29 | return (first1 == last1 && first2 == last2); 30 | } 31 | } 32 | } 33 | #endif -------------------------------------------------------------------------------- /test/vectorTest.cpp: -------------------------------------------------------------------------------- 1 | #include "VectorTest.h" 2 | 3 | namespace EasySTL { 4 | namespace VectorTest { 5 | void testCase1(){ 6 | //std::string old_SGI_vector = "old_SGI_vector"; 7 | //std::string new_EasySTL_vector = "new_EasySTL_vector"; 8 | //stdVec v1(10, "zzz"); 9 | easyVec v1 = {"1","2","3","4"}; 10 | easyVec v2 = {"1","2","3","5"}; 11 | //EasySTL::Test::print_container(v1, "SGI_vector"); 12 | if (v1 == v2) std::cout<<"equal" < v3 = {"abc","cba","dca","ghj"}; 17 | //EasySTL::Test::print_container(v3, "v3"); 18 | // std::string a = "huyun"; 19 | // v2.push_back(a); 20 | 21 | // EasySTL::Test::print_container(v2, "push_back"); 22 | 23 | // v2.pop_back(); 24 | 25 | // EasySTL::Test::print_container(v2, "pop_back"); 26 | 27 | //auto p = v2.begin(); 28 | 29 | //auto q = p + 2; 30 | 31 | // std::cout << "the second one" <<*p < 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | namespace EasySTL { 14 | namespace VectorTest{ 15 | template 16 | using stdVec = std::vector < T >; 17 | 18 | template 19 | using easyVec = EasySTL::vector < T >; 20 | 21 | void testCase1(); 22 | } 23 | } 24 | #endif -------------------------------------------------------------------------------- /typetraits.h: -------------------------------------------------------------------------------- 1 | #ifndef _TYPE_TRAITS_H_ 2 | #define _TYPE_TRAITS_H_ 3 | 4 | namespace EasySTL { 5 | 6 | 7 | struct _true_type { }; 8 | 9 | struct _false_type { }; 10 | 11 | 12 | 13 | /* 14 | 15 | ** 萃取传入的T类型的类型特性 16 | 17 | */ 18 | 19 | template 20 | 21 | struct _type_traits 22 | 23 | { 24 | 25 | typedef _false_type has_trivial_default_constructor; 26 | 27 | typedef _false_type has_trivial_copy_constructor; 28 | 29 | typedef _false_type has_trivial_assignment_operator; 30 | 31 | typedef _false_type has_trivial_destructor; 32 | 33 | typedef _false_type is_POD_type; 34 | 35 | }; 36 | 37 | 38 | 39 | template<> 40 | 41 | struct _type_traits 42 | 43 | { 44 | 45 | typedef _true_type has_trivial_default_constructor; 46 | 47 | typedef _true_type has_trivial_copy_constructor; 48 | 49 | typedef _true_type has_trivial_assignment_operator; 50 | 51 | typedef _true_type has_trivial_destructor; 52 | 53 | typedef _true_type is_POD_type; 54 | 55 | }; 56 | 57 | template<> 58 | 59 | struct _type_traits 60 | 61 | { 62 | 63 | typedef _true_type has_trivial_default_constructor; 64 | 65 | typedef _true_type has_trivial_copy_constructor; 66 | 67 | typedef _true_type has_trivial_assignment_operator; 68 | 69 | typedef _true_type has_trivial_destructor; 70 | 71 | typedef _true_type is_POD_type; 72 | 73 | }; 74 | 75 | template<> 76 | 77 | struct _type_traits 78 | 79 | { 80 | 81 | typedef _true_type has_trivial_default_constructor; 82 | 83 | typedef _true_type has_trivial_copy_constructor; 84 | 85 | typedef _true_type has_trivial_assignment_operator; 86 | 87 | typedef _true_type has_trivial_destructor; 88 | 89 | typedef _true_type is_POD_type; 90 | 91 | }; 92 | 93 | template<> 94 | 95 | struct _type_traits 96 | 97 | { 98 | 99 | typedef _true_type has_trivial_default_constructor; 100 | 101 | typedef _true_type has_trivial_copy_constructor; 102 | 103 | typedef _true_type has_trivial_assignment_operator; 104 | 105 | typedef _true_type has_trivial_destructor; 106 | 107 | typedef _true_type is_POD_type; 108 | 109 | }; 110 | 111 | template<> 112 | 113 | struct _type_traits 114 | 115 | { 116 | 117 | typedef _true_type has_trivial_default_constructor; 118 | 119 | typedef _true_type has_trivial_copy_constructor; 120 | 121 | typedef _true_type has_trivial_assignment_operator; 122 | 123 | typedef _true_type has_trivial_destructor; 124 | 125 | typedef _true_type is_POD_type; 126 | 127 | }; 128 | 129 | template<> 130 | 131 | struct _type_traits 132 | 133 | { 134 | 135 | typedef _true_type has_trivial_default_constructor; 136 | 137 | typedef _true_type has_trivial_copy_constructor; 138 | 139 | typedef _true_type has_trivial_assignment_operator; 140 | 141 | typedef _true_type has_trivial_destructor; 142 | 143 | typedef _true_type is_POD_type; 144 | 145 | }; 146 | 147 | template<> 148 | 149 | struct _type_traits 150 | 151 | { 152 | 153 | typedef _true_type has_trivial_default_constructor; 154 | 155 | typedef _true_type has_trivial_copy_constructor; 156 | 157 | typedef _true_type has_trivial_assignment_operator; 158 | 159 | typedef _true_type has_trivial_destructor; 160 | 161 | typedef _true_type is_POD_type; 162 | 163 | }; 164 | 165 | template<> 166 | 167 | struct _type_traits 168 | 169 | { 170 | 171 | typedef _true_type has_trivial_default_constructor; 172 | 173 | typedef _true_type has_trivial_copy_constructor; 174 | 175 | typedef _true_type has_trivial_assignment_operator; 176 | 177 | typedef _true_type has_trivial_destructor; 178 | 179 | typedef _true_type is_POD_type; 180 | 181 | }; 182 | 183 | template<> 184 | 185 | struct _type_traits 186 | 187 | { 188 | 189 | typedef _true_type has_trivial_default_constructor; 190 | 191 | typedef _true_type has_trivial_copy_constructor; 192 | 193 | typedef _true_type has_trivial_assignment_operator; 194 | 195 | typedef _true_type has_trivial_destructor; 196 | 197 | typedef _true_type is_POD_type; 198 | 199 | }; 200 | 201 | template<> 202 | 203 | struct _type_traits 204 | 205 | { 206 | 207 | typedef _true_type has_trivial_default_constructor; 208 | 209 | typedef _true_type has_trivial_copy_constructor; 210 | 211 | typedef _true_type has_trivial_assignment_operator; 212 | 213 | typedef _true_type has_trivial_destructor; 214 | 215 | typedef _true_type is_POD_type; 216 | 217 | }; 218 | 219 | template<> 220 | 221 | struct _type_traits 222 | 223 | { 224 | 225 | typedef _true_type has_trivial_default_constructor; 226 | 227 | typedef _true_type has_trivial_copy_constructor; 228 | 229 | typedef _true_type has_trivial_assignment_operator; 230 | 231 | typedef _true_type has_trivial_destructor; 232 | 233 | typedef _true_type is_POD_type; 234 | 235 | }; 236 | 237 | template<> 238 | 239 | struct _type_traits 240 | 241 | { 242 | 243 | typedef _true_type has_trivial_default_constructor; 244 | 245 | typedef _true_type has_trivial_copy_constructor; 246 | 247 | typedef _true_type has_trivial_assignment_operator; 248 | 249 | typedef _true_type has_trivial_destructor; 250 | 251 | typedef _true_type is_POD_type; 252 | 253 | }; 254 | 255 | template<> 256 | 257 | struct _type_traits 258 | 259 | { 260 | 261 | typedef _true_type has_trivial_default_constructor; 262 | 263 | typedef _true_type has_trivial_copy_constructor; 264 | 265 | typedef _true_type has_trivial_assignment_operator; 266 | 267 | typedef _true_type has_trivial_destructor; 268 | 269 | typedef _true_type is_POD_type; 270 | 271 | }; 272 | 273 | template<> 274 | 275 | struct _type_traits 276 | 277 | { 278 | 279 | typedef _true_type has_trivial_default_constructor; 280 | 281 | typedef _true_type has_trivial_copy_constructor; 282 | 283 | typedef _true_type has_trivial_assignment_operator; 284 | 285 | typedef _true_type has_trivial_destructor; 286 | 287 | typedef _true_type is_POD_type; 288 | 289 | }; 290 | 291 | template<> 292 | 293 | struct _type_traits 294 | 295 | { 296 | 297 | typedef _true_type has_trivial_default_constructor; 298 | 299 | typedef _true_type has_trivial_copy_constructor; 300 | 301 | typedef _true_type has_trivial_assignment_operator; 302 | 303 | typedef _true_type has_trivial_destructor; 304 | 305 | typedef _true_type is_POD_type; 306 | 307 | }; 308 | 309 | template<> 310 | 311 | struct _type_traits 312 | 313 | { 314 | 315 | typedef _true_type has_trivial_default_constructor; 316 | 317 | typedef _true_type has_trivial_copy_constructor; 318 | 319 | typedef _true_type has_trivial_assignment_operator; 320 | 321 | typedef _true_type has_trivial_destructor; 322 | 323 | typedef _true_type is_POD_type; 324 | 325 | }; 326 | 327 | 328 | //指针是POD类型 329 | template 330 | 331 | struct _type_traits 332 | 333 | { 334 | 335 | typedef _true_type has_trivial_default_constructor; 336 | 337 | typedef _true_type has_trivial_copy_constructor; 338 | 339 | typedef _true_type has_trivial_assignment_operator; 340 | 341 | typedef _true_type has_trivial_destructor; 342 | 343 | typedef _true_type is_POD_type; 344 | 345 | }; 346 | 347 | template 348 | 349 | struct _type_traits 350 | 351 | { 352 | 353 | typedef _true_type has_trivial_default_constructor; 354 | 355 | typedef _true_type has_trivial_copy_constructor; 356 | 357 | typedef _true_type has_trivial_assignment_operator; 358 | 359 | typedef _true_type has_trivial_destructor; 360 | 361 | typedef _true_type is_POD_type; 362 | 363 | }; 364 | 365 | template<> 366 | 367 | struct _type_traits 368 | 369 | { 370 | 371 | typedef _true_type has_trivial_default_constructor; 372 | 373 | typedef _true_type has_trivial_copy_constructor; 374 | 375 | typedef _true_type has_trivial_assignment_operator; 376 | 377 | typedef _true_type has_trivial_destructor; 378 | 379 | typedef _true_type is_POD_type; 380 | 381 | }; 382 | 383 | template<> 384 | 385 | struct _type_traits 386 | 387 | { 388 | 389 | typedef _true_type has_trivial_default_constructor; 390 | 391 | typedef _true_type has_trivial_copy_constructor; 392 | 393 | typedef _true_type has_trivial_assignment_operator; 394 | 395 | typedef _true_type has_trivial_destructor; 396 | 397 | typedef _true_type is_POD_type; 398 | 399 | }; 400 | 401 | template<> 402 | 403 | struct _type_traits 404 | 405 | { 406 | 407 | typedef _true_type has_trivial_default_constructor; 408 | 409 | typedef _true_type has_trivial_copy_constructor; 410 | 411 | typedef _true_type has_trivial_assignment_operator; 412 | 413 | typedef _true_type has_trivial_destructor; 414 | 415 | typedef _true_type is_POD_type; 416 | 417 | }; 418 | 419 | template<> 420 | 421 | struct _type_traits 422 | 423 | { 424 | 425 | typedef _true_type has_trivial_default_constructor; 426 | 427 | typedef _true_type has_trivial_copy_constructor; 428 | 429 | typedef _true_type has_trivial_assignment_operator; 430 | 431 | typedef _true_type has_trivial_destructor; 432 | 433 | typedef _true_type is_POD_type; 434 | 435 | }; 436 | 437 | template<> 438 | 439 | struct _type_traits 440 | 441 | { 442 | 443 | typedef _true_type has_trivial_default_constructor; 444 | 445 | typedef _true_type has_trivial_copy_constructor; 446 | 447 | typedef _true_type has_trivial_assignment_operator; 448 | 449 | typedef _true_type has_trivial_destructor; 450 | 451 | typedef _true_type is_POD_type; 452 | 453 | }; 454 | 455 | template<> 456 | 457 | struct _type_traits 458 | 459 | { 460 | 461 | typedef _true_type has_trivial_default_constructor; 462 | 463 | typedef _true_type has_trivial_copy_constructor; 464 | 465 | typedef _true_type has_trivial_assignment_operator; 466 | 467 | typedef _true_type has_trivial_destructor; 468 | 469 | typedef _true_type is_POD_type; 470 | 471 | }; 472 | 473 | 474 | 475 | } 476 | 477 | #endif -------------------------------------------------------------------------------- /uninitialized.h: -------------------------------------------------------------------------------- 1 | #ifndef _UNINITIALIZED_H_ 2 | #define _UNINITIALIZED_H_ 3 | 4 | #include "construct.h" 5 | //#include "iterator.h" 6 | //#include "typetraits.h" 7 | #include "algorithm.h" 8 | namespace EasySTL { 9 | 10 | /* 11 | * 未初始化的拷贝,在已获得的内存上创建一些元素 12 | */ 13 | //POD版本的未初始化拷贝 14 | template 15 | ForwardIterator _unitialized_copy_aux(InputIterator first, InputIterator last, 16 | ForwardIterator result, _true_type) { 17 | //从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中 18 | memcpy(result, first, (last - first) * sizeof(*first)); 19 | return result + (last - first); 20 | } 21 | 22 | //非POD版本的未初始化拷贝 23 | template 24 | ForwardIterator _unitialized_copy_aux(InputIterator first, InputIterator last, 25 | ForwardIterator result, _false_type) { 26 | int i = 0; 27 | for (; first != last; ++first, ++i) { 28 | construct(result + i, *first); 29 | } 30 | return (result + i); 31 | } 32 | 33 | template 34 | ForwardIterator _unitialized_copy(InputIterator first, InputIterator last, 35 | ForwardIterator result, T) { 36 | typedef typename _type_traits::is_POD_type isPOD; 37 | return _unitialized_copy_aux(first, last, result, isPOD()); 38 | } 39 | 40 | template 41 | ForwardIterator unitialized_copy(InputIterator first, InputIterator last, 42 | ForwardIterator result) { 43 | _unitialized_copy(first, last, result, value_type(result)); 44 | 45 | } 46 | 47 | /* 48 | * 未初始化的拷贝,以某一特定值初始化 49 | */ 50 | template 51 | void _unitialized_fill_aux(ForwardIterator first, ForwardIterator last, 52 | const T& value, _true_type) { 53 | fill(first, last, value); 54 | } 55 | 56 | template 57 | void _unitialized_fill_aux(ForwardIterator first, ForwardIterator last, 58 | const T& value, _false_type) { 59 | for (;first != last; ++first) { 60 | construct(first, value); 61 | } 62 | } 63 | 64 | template 65 | void unitialized_fill(ForwardIterator first, ForwardIterator last, 66 | const T& value) { 67 | typedef typename _type_traits::is_POD_type isPOD; 68 | _unitialized_fill_aux(first, last, value, isPOD()); 69 | } 70 | 71 | /* 72 | * 未初始化的拷贝,以某一特定数量n初始化 73 | */ 74 | template 75 | ForwardIterator _unitialized_fill_n_aux(ForwardIterator first, Size n, 76 | const T& x, _true_type) { 77 | return fill_n(first, n, x); 78 | } 79 | 80 | template 81 | ForwardIterator _unitialized_fill_n_aux(ForwardIterator first, Size n, 82 | const T& x, _false_type) { 83 | int i = 0; 84 | for(; i != n; ++i) { 85 | construct((T*)(first + i), x); 86 | } 87 | return (first + i); 88 | } 89 | 90 | template 91 | inline ForwardIterator unitialized_fill_n(ForwardIterator first ,Size n, 92 | const T& x) { 93 | typedef typename _type_traits::is_POD_type isPOD; 94 | _unitialized_fill_n_aux(first, n, x, isPOD()); 95 | } 96 | } 97 | #endif -------------------------------------------------------------------------------- /vector.h: -------------------------------------------------------------------------------- 1 | #ifndef _VECTOR_H_ 2 | #define _VECTOR_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "allocator.h" 10 | #include "algorithm.h" 11 | #include "iterator.h" 12 | //#include "construct.h" 13 | #include "uninitialized.h" 14 | 15 | namespace EasySTL { 16 | /******** vector ***********/ 17 | template 18 | class vector { 19 | public: 20 | //vector的嵌套型别定义 21 | typedef T value_type; 22 | typedef T* pointer; 23 | typedef T* iterator; 24 | typedef const T* const_pointer; 25 | typedef T& reference; 26 | typedef size_t size_type; 27 | typedef ptrdiff_t difference_type; 28 | 29 | protected: 30 | //simple_alloc 是空间配置器 31 | typedef simple_alloc data_allocator; 32 | 33 | iterator start_; //目前使用空间头 34 | iterator finish_;//目前使用空间尾 35 | iterator end_of_storage_;//目前可用空间的尾 36 | 37 | void insert_aux(iterator position, const T& x); 38 | //void insert(iterator position, size_type n, const T& x); 39 | 40 | void deallocate() { 41 | if (start_) { 42 | data_allocator::deallocate(start_, end_of_storage_ - start_); 43 | } 44 | } 45 | 46 | void fill_initialize(size_type n, const T& value) { 47 | start_ = allocate_and_fill(n, value); 48 | finish_ = start_ + n; 49 | end_of_storage_ = finish_; 50 | } 51 | 52 | public: 53 | iterator begin() const { return start_;} 54 | iterator end() const { return finish_;} 55 | size_type size() const { return size_type(end() - begin());} 56 | size_type capacity() const { return size_type(end_of_storage_ - begin());} 57 | bool empty() const { return begin() == end();} 58 | reference operator[](size_type n) {return *(begin() + n);} 59 | bool operator ==(const vector& other) const { 60 | auto first1 = begin(), last1 = end(); 61 | auto first2 = other.begin(), last2 = other.end(); 62 | for (; first1 != last1 && first2 != last2; ++first1, ++first2){ 63 | if (*first1 != *first2) 64 | return false; 65 | } 66 | return (first1 == last1 && first2 == last2); 67 | 68 | } 69 | 70 | vector() : start_(0), finish_(0), end_of_storage_(0) {} 71 | vector(size_type n, const T& value) { fill_initialize(n, value);} 72 | vector(int n, const T& value) { fill_initialize(n, value);} 73 | vector(long n, const T& value) { fill_initialize(n, value);} 74 | vector(const std::initializer_list v) { 75 | auto start_v = v.begin(); 76 | auto end_v = v.end(); 77 | size_type n = v.size(); 78 | fill_initialize(n, T()); 79 | finish_ = EasySTL::copy(start_v, end_v, start_); 80 | } 81 | explicit vector(size_type n) {fill_initialize(n, T());} 82 | 83 | ~vector() { 84 | destroy(start_, finish_); //construct.h中的函数 85 | deallocate(); //vector的成员函数 86 | } 87 | 88 | reference front() { return *begin();} 89 | reference back() { return *end();} 90 | void push_back(const T& x) { 91 | if (finish_ != end_of_storage_) { 92 | construct(finish_, x); 93 | finish_++; 94 | } else { 95 | insert_aux(end(), x); 96 | } 97 | } 98 | 99 | void pop_back() { 100 | --finish_; 101 | destroy(finish_); 102 | } 103 | 104 | void insert(iterator position, size_type n, const T& x); 105 | 106 | iterator erase(iterator position) { 107 | if (position + 1 != end()) 108 | EasySTL::copy(position + 1, finish_, position); 109 | finish_--; 110 | destroy(finish_); 111 | return position; 112 | } 113 | 114 | iterator erase(iterator start_earse, iterator end_earse) { 115 | size_type erase_size = end_earse - start_earse; //总共去掉多少元素 116 | 117 | if (end_earse + 1 != end()) { 118 | size_type left = finish_ - end_earse; //去掉中间一段后,尾巴上还有多少元素 119 | EasySTL::copy(end_earse, finish_, start_earse); 120 | destroy(start_earse + left, finish_); 121 | } else { 122 | destroy(start_earse, finish_); 123 | } 124 | finish_ = finish_ - erase_size; 125 | return start_earse; 126 | } 127 | 128 | //调整容器大小,如果newsize小于原大小,则清空多余部分 129 | //如果大于原大小,则从尾部插入 130 | void resize(size_type new_size, const T& x) { 131 | if (new_size < size()) 132 | erase(begin() + new_size, end()); 133 | else 134 | insert(end(), new_size - size(), x); 135 | } 136 | 137 | void resize(size_type new_size) { resize(new_size, T());} 138 | void clear() { erase(begin(), end());} 139 | 140 | protected: 141 | //分配n个元素大小空间,并以x初始化 142 | iterator allocate_and_fill(size_type n, const T& x) { 143 | //获取内存空间 144 | iterator result = data_allocator::allocate(n); 145 | //在获取到的内存上创建对象 146 | unitialized_fill_n(result, n, x); 147 | return result; 148 | } 149 | }; 150 | 151 | template 152 | void vector::insert(iterator position, size_type n, const T& x) { 153 | //从position的位置插入n个元素,元素初始值为x 154 | std::cout << "i'm in" <= n) { 159 | //内存的空间可以装下新增加的元素 160 | const size_type elems_after = finish_ - position; 161 | unitialized_fill_n(finish_, n, x_copy); 162 | 163 | EasySTL::copy(position, finish_, position + n); 164 | 165 | EasySTL::fill(position, position + n, x_copy); 166 | 167 | finish_ += n; 168 | } else { 169 | //内存空间不足以装下新增加的元素 170 | const size_type old_size = size(); 171 | const size_type new_size = old_size + std::max(old_size, n); 172 | 173 | iterator new_start = data_allocator::allocate(new_size); 174 | if (!new_start) { 175 | std::cout << "out_of_memory" < 202 | void vector::insert_aux(iterator position, const T& x) { 203 | if (finish_ != end_of_storage_) { 204 | //还有备用空间 205 | //在备用空间开始处创建一个对象,并以vector的最后一个对象为初始值 206 | construct(finish_, *(finish_ - 1)); 207 | ++finish_; 208 | T x_copy = x; 209 | copy_backward(position, finish_ - 2, finish_ - 1); 210 | *position = x_copy; //position上是已经有构造好的对象,直接赋值就可以 211 | } else { 212 | //没有可用空间 213 | const size_type old_size = size(); 214 | //内存不足则申请原来两倍的新内存 215 | const size_type new_size = old_size != 0 ? 2 * old_size : 1; 216 | 217 | iterator new_start = data_allocator::allocate(new_size); 218 | iterator new_finish = new_start; 219 | try { 220 | new_finish = uninitialized_copy(start_, position, new_start); 221 | construct(new_finish ,x); //未构造的内存,需要调用construct 222 | new_finish++; 223 | new_finish = uninitialized_copy(position, finish_, new_finish); 224 | } catch (...) { 225 | //出现异常,回滚 226 | destroy(new_start, new_finish); 227 | data_allocator::deallocate(new_start, new_size); 228 | throw; 229 | } 230 | 231 | destroy(begin(), end());//销毁原来的vector内存空间 232 | deallocate(); 233 | 234 | start_ = new_start; 235 | finish_ = new_finish; 236 | end_of_storage_ = new_start + new_size; 237 | } 238 | } 239 | } 240 | 241 | #endif --------------------------------------------------------------------------------