vector的自定义实现

  1 #pragma warning(disable:4996)
  2 #include<iostream>
  3 #include<string>
  4 #include<vector>
  5 #include<algorithm>
  6 #include<cstdio>
  7 #include<complex>
  8 #include<new>
  9 #include<memory>
 10 #include<exception>
 11 #include<cstdlib>
 12 #include<iterator>
 13 #include<initializer_list>
 14 using namespace std;
 15 //template<typename t> class alloc
 16 //{public:
 17 //    alloc():a(),s(){ //成员变量默认初始化
 18 //    }
 19 //    t* allocate(size_t n){
 20 //        return a.allocate(n);
 21 //    }
 22 ////变长模板参数,allocator的第二个参数是变长的,要调用它,外层的construct也要有变长参数
 23 //template<typename...Args>    void construct(t* p, const Args&...rest){
 24 //        a.construct(p,rest... );
 25 //    }
 26 //    void deallocate(t* p, size_t n)
 27 //    {
 28 //        a.deallocate(p, n);
 29 //    }
 30 //    void destory(t* p)
 31 //    {
 32 //        a.destory(p);
 33 //    }
 34 //
 35 //
 36 //private:
 37 //    allocator<t> a;
 38 //    string s;
 39 //
 40 //};
 41 //vector为空,capacity=0,否则预分配空间为16,当空间不足时,扩大两倍增长,
 42 template<typename T, class Allocator = std::allocator<T> >
 43 class Vector{
 44 private:
 45     T* start;
 46     T* finish;
 47     T* end_of_storage;
 48     size_t length;
 49     size_t capacity;
 50 public:
 51     typedef T* iterator;
 52     typedef const T* const_iterator;
 53     Vector():start(NULL),finish(0){
 54     end_of_storage = NULL;
 55     length = 0;
 56     capacity = 0;
 57     }
 58     Vector(const std::initializer_list<T> &lst)
 59     {
 60         for (auto it = lst.begin(); it != lst.end();it++)
 61         {
 62             this->push_back(*it);
 63         }
 64
 65     }
 66     Vector(size_t n, const T&value = T()){
 67         Allocator a;
 68         T*p = NULL;
 69         if (n <= 16){ p = a.allocate(16);
 70         capacity = 16;
 71         }
 72         else {
 73             p = a.allocate(static_cast<int>(1.5 * n));
 74             capacity = static_cast<size_t>(1.5*n);
 75         }
 76         start = p;
 77         finish=uninitialized_fill_n(p, n, value);
 78         if (n <= 16) end_of_storage = start + 15;
 79         else     end_of_storage = p + static_cast<int>(1.5*n)-1;
 80         length = n;
 81     }
 82     /*Vector(size_t n, const T&value){ Vector(n, value); }*/
 83     Vector(const Vector& rhs){
 84         capacity = rhs.capacity;
 85         length = rhs.length;
 86         Allocator a;
 87         start=a.allocate(capacity);
 88         end_of_storage = start + capacity - 1;
 89         finish = start + length ;
 90
 91         for (T* p = start,*q = rhs.start; p != finish; p++, q++){
 92             a.construct(p, *q);
 93         }
 94     }
 95     void push_back(const T& value){
 96         if (capacity == 0){ //为空容器时需要申请新空间
 97             Allocator a;
 98              start = a.allocate(16);
 99             a.construct(start, value);
100             finish = start + 1;
101             end_of_storage = start + 15;
102             length = 1;
103             capacity = 16;
104         }
105         else if (length < capacity){
106             Allocator a;
107             a.construct(finish++, value);
108             length += 1;
109         }
110         else { //空间不足时1.5倍扩大空间
111             Allocator a;
112             auto old_capacity = capacity;
113             auto new_start = a.allocate(static_cast<size_t>(1.5*capacity));
114             auto new_finish = uninitialized_copy(this->begin(), this->begin()+length, new_start); //没有使用迭代器形式
115             new_finish = uninitialized_fill_n(new_finish, 1, value);
116             //释放掉旧空间
117             capacity = static_cast<size_t>(1.5*capacity);
118             length += 1;
119
120             auto temp = start;
121             while (temp != finish)
122             {
123                 a.destroy(temp++);
124             }
125             a.deallocate(start, old_capacity);
126             start = new_start;
127             finish = new_finish;
128             end_of_storage = start + capacity - 1;
129         }
130     }
131     void pop_back(){//弹出的意义是不在含有该对象
132         Allocator a;
133         a.destroy(--finish); //finish指向尾后位置,自减后销毁了对象,不存在了
134         length -= 1;
135
136     }
137     iterator insert(const_iterator position, const T&value);
138     T& operator[](size_t n){return *(start + n); } //如果index out of bound or Vector为空 ,让用户自己去处理
139     const T& operator[](size_t n)const {  return *(start + n); }
140     T& front(){ return *start; }
141     const T&front()const{ return *start; }
142     T& back(){ return *(finish-1); }
143     const T&back()const{ return *(finish - 1); }
144     size_t size(){ return length; }
145     size_t volume(){ return capacity; }
146     iterator begin(){ return start; }
147     const_iterator cbegin()const { return start; }
148     iterator end(){ return finish; }
149     const_iterator cend(){ return finish; }
150     Vector& operator=(const Vector&rhs){
151         if (this->start ==rhs.start) return *this; //两个相等,两个相同
152         //释放掉原有的内存空间,allocator分配的空间如果不deallocate,会造成内存泄漏
153         auto old_start = this->start;
154         auto old_finish = this->finish;
155         size_t old_capacity = this->capacity;
156         capacity = rhs.capacity;
157         length = rhs.length;
158         Allocator a;
159         start = a.allocate(capacity);
160         end_of_storage = start + capacity - 1;
161         finish = start + length;
162
163         for (T* p = start, *q = rhs.start; p != finish; p++, q++){
164             a.construct(p, *q);
165         }
166         Allocator b;//是需要重新创建b,还是用前面的a就可以完成下面的动作
167         T* p = old_start;
168         while (p!=old_finish)
169         {
170             b.destroy(p++);
171         }
172         b.deallocate(old_start, old_capacity);
173         return *this;
174
175     };
176     ~Vector(){
177         Allocator a;
178         T* p = start;
179         while (p!= finish)
180         {
181             a.destroy(p++);
182         }
183         a.deallocate(start, capacity);
184         start = finish = end_of_storage = NULL; //是否多余语句
185         cout << " dectr completed";
186     }
187
188 };
189 template<typename T>
190 class demo{
191 public:
192     demo():d(){}
193     T size();
194 private:
195     T d;
196 };
197 class foo{
198 public:
199     foo() :a(5), s("dka"){}
200 private:
201     int a; string s;
202
203 };
204
205 int main()
206 {
207     Vector<string> v1;
208     cout << v1.volume() << " " << v1.size() << "\n";
209     Vector<string> v2(10);//10个空串,调用了string的default ctr
210     cout << v2.size() << " " << v2.volume() << endl;
211     cout << "the first item of v2: " << v2[0] << " or " << v2.front() << endl;
212     //Vector<string> v3(10, ‘c‘); no instance of parameters (int,char)
213     Vector<string> v4(10, "c");
214     Vector<string> v5(v4);
215     cout << v5.back() << " " << v5.size() << v5.volume() << endl;
216     v5 = v1;
217     for (auto it = v5.begin(); it!= v5.end();it++)
218     {
219         cout << *it;
220     }
221     /*cout << v5[0] << endl;*/
222
223     Vector<string> v6(v1); //用空vector初始化另一个vector ;这两个vector都应该表现正常
224     for (auto it = v6.cbegin(); it != v6.cend();it++)
225     {
226         cout << *it << endl;
227     }
228     v1 = v4;//v1原本为空,用含10个元素的v4赋值,并用push_back添加尾元素
229     for (auto x : v1) cout << x << endl;
230     v1.push_back("hdwa");
231     cout << v1.size() << v1[10] << endl;
232     v1.pop_back();
233     cout << v1.back() << endl;
234     string s;
235     Vector<int> iv(10);
236     for (auto y:iv)
237     {
238         printf("%d", y);
239     }
240     Vector<string> v7={ "dak", "dj" };
241     cout << v7.volume() << " " << v7.size() << v7[0] << " " << v7[1] << endl;
242
243
244 }

时间: 2024-12-12 09:44:38

vector的自定义实现的相关文章

关于vector中自定义sort排序规则

本文是从我一个实际的程序摘出来,因此没有太多的叙述性的东西 首先呢 sort需要一个头文件  #include<algorithm> 这种排序主要针对的是自定义的vector类型 如: typedef struct AD {     int len;     string name; }ad; vector<ad> adtemp; 对adtemp排序,首先需要自己设定排序规则,当然了还是根据int型变量比较好排序啦,因为是自定义结构体所以方便和实用为关键哈 ok 排序规则 //这是

C++ STL vector容器学习

STL(Standard Template Library)标准模板库是C++最重要的组成部分,它提供了一组表示容器.迭代器.函数对象和算法的模板.其中容器是存储类型相同的数据的结构(如vector,list, deque, set, map等),算法完成特定任务,迭代器用来遍历容器对象,扮演容器和算法之间的胶合剂. 模板类vector 在计算中,矢量(vector)对应数组,它的数据安排以及操作方式,与array非常类似.在C++中,使用vector模板类时,需要头文件包含#include<v

Vector源码分析

源码版本为JDK1.7.0_75. public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable Vector继承了AbstractList,实现了List接口,可以被当作list使用:实现了RandomAccess接口,该接口是一个标记接口,表明该类支持快速随机访问:实现了Cloneable接口,说明该类可

C++三种容器:list、vector和deque的区别

在写C++程序的时候会发现STL是一个不错的东西,减少了代码量,使代码的复用率大大提高,减轻了程序猿的负担.还有一个就是容器,你会发现要是自己写一个链表.队列,或者是数组的时候,既要花时间还要操心怎么去维护,里面的指针啊,内存够不够用啊,长度问题,有没有可能溢出啊等等一系列的问题等着我们去解决,还是比较头疼的.所以容器的出现解决了这一个问题,它将这些数据结构都封装成了一个类,只需要加上头文件,我们就可以轻松的应用,不用那么复杂,就连指针也被封装成了迭代器,用起来更方便,更人性化,方便了我们的编程

C++/STL中 vector中对 “=”赋值运算符的支持

由于好奇STL中的vector 对于自定义数据类型的 " = "(赋值运算符的)支持,谢了一段简单的测试代码进行测试. 结果证明vector对于赋值预算符支持良好,但是对于动态分配的类构成的vector数组, 博主认为一定要重写析构函数与复制构造函数以及运算符重载"="运算符(这是一条软件规则,详见博主测试),链接如下: http://blog.csdn.net/u010003835/article/details/47314811 测试代码: #include &

C++ vector,list,deque区别(转)

  在写C++程序的时候会发现STL是一个不错的东西,减少了代码量,使代码的复用率大大提高,减轻了程序猿的负担.还有一个就是容器,你会发现要是自己写一个链表.队列,或者是数组的时候,既要花时间还要操心怎么去维护,里面的指针啊,内存够不够用啊,长度问题,有没有可能溢出啊等等一系列的问题等着我们去解决,还是比较头疼的.所以容器的出现解决了这一个问题,它将这些数据结构都封装成了一个类,只需要加上头文件,我们就可以轻松的应用,不用那么复杂,就连指针也被封装成了迭代器,用起来更方便,更人性化,方便了我们的

深入解析 Java集合类ArrayList与Vector的区别

集合类分为两个分支,Collection与Map,其中Collection接口继承了Iterator接口,继承Iterator接口的类可以使用迭代器遍历元素(即Collection接口的类都可以使用),今天我们从相同点.不同点.以及JDK源码等各个方面来深入解析下,底层使用数组实现的两个集合类:ArrayList与Vector的区别与联系 区别与联系: 1.ArrayList出现于jdk1.2,vector出现于1.0.两者底层的数据存储都使用的Object数组实现,因为是数组实现,所以具有查找

javase基础

目录 目录... 1 第一天... 5 1:计算机概述(了解) 5 2:键盘功能键的认识和快捷键(掌握) 5 3:常见的DOS命令(掌握) 6 4:Java语言概述(了解) 6 5:JDK,JRE,JVM的作用及关系(掌握) 7 6:JDK的下载,安装,卸载(掌握) 7 7:第一个程序:HelloWorld案例(掌握) 7 8:常见的问题(掌握) 8 9:path环境变量(掌握) 8 10:classpath环境变量(理解) 8 第二天... 10 1:关键字(掌握) 10 2:标识符(掌握)

java12

1:List的子类(掌握) (1)List的子类特点 ArrayList: 底层数据结构是数组,查询快,增删慢 线程不安全,效率高 Vector: 底层数据结构是数组,查询快,增删慢 线程安全,效率低 LinkedList: 底层数据结构是链表,查询慢,增删快 线程不安全,效率高 (2)ArrayList A:没有特有功能需要学习 B:案例 a:ArrayList存储字符串并遍历 b:ArrayList存储自定义对象并遍历 (3)Vector A:有特有功能 a:添加 public void a