vector的实现【C++】
来源:互联网 发布:搞笑淘宝买家秀图聊天 编辑:程序博客网 时间:2024/05/18 01:11
平时都是直接使用C++标准库中的容器,今天就参照《数据结构与算法分析》一书简单的实现了下vector向量容器,本程序中没有添加异常以及错误的处理。后期会继续完善。
#include<iostream>#include<List>using namespace std;template<typename Object>class Vector{public: explicit Vector(int initSize = 0) :theSize(initSize),theCapactity(initSize+SPARE_CAPACITY) {objects = new Object[theCapactity];} Vector(const Vector& rhs):objects(NULL) {operator=(rhs);} ~Vector() {delete [] objects;} const Vector& operator=(const Vector& rhs) { if(this!=rhs) { delete [] objects; theSize = rhs.size(); theCapactity = rhs.theCapactity(); objects = new Object[capacity()]; for(int k = 0;k < size();k++) objects[k] = rhs.objects[k]; } return *this; } void resize(int newSize) { if(newSize < theSize) reserve(newSize*2+1); theSize = newSize; } void reserve(int newCapacity) { if(newCapacity < theSize) return; Object* oldArray = objects; objects = new Object[newCapacity]; for(int k = 0;k<theSize;k++) objects[k] = oldArray[k]; theCapactity = newCapacity; delete [] oldArray; } Object& operator[](int index) { return objects[index]; } const Object& operator[](int index) const {return objects[index];} bool empty() const {return size() == 0;} int size() const {return theSize;} int capacity() const {return theCapactity;} void push_back(const Object & x) { if(theSize == theCapactity) reserve(2*theCapactity + 1); objects[theSize++] = x; } void pop_back() {theSize--;} const Object & back() const {return objects[theSize - 1];} typedef Object * iterator; typedef const Object * const_iterator; iterator begin() {return &objects[0];} const_iterator begin() const {return &objects[0];} iterator end() {return &objects[size()];} const_iterator end() const {return &objects[size()];} enum {SPARE_CAPACITY = 16};private: int theSize; int theCapactity; Object * objects;};int main(int argc,char** argv){ //list<int> A; //system("pasue"); Vector<Vector<int>> CC; Vector<int> BB; Vector<int> A; int a = 1; A.push_back(a); A.push_back(2); A.push_back(3); cout<<"A's size is"<<A.size()<<endl; for(int i =0 ;i < A.size();i++) cout<<"A:"<<A[i]<<endl; A.pop_back(); for(int i =0 ;i < A.size();i++) cout<<"A' is:"<<A[i]<<endl; system("pause"); return 0;}
阅读全文
0 0
- vector的实现【C++】
- C实现的类似vector的容器
- c/c++ vector 的简单实现
- 基于vector的栈实现(C++)
- Vector 的简单实现 C++11
- [C++]vector 的 push_back实现原理
- (C++)Vector 简单的底层实现
- C语言实现 vector
- c实现vector
- c++vector简单实现
- [C++]Vector源码实现
- 【C++】实现容器Vector
- c++:模拟实现vector
- 压榨编译器,用宏+C实现STL的VECTOR
- C语言实现类似于C++的Vector容器
- C.Interface.And.Implementations—bit vector的实现
- C++STL之vector,实现属于自己的my_vector
- (C++)vector & list 的使用和模拟实现
- java简单界面实现
- Day01
- 总结5(作业3)
- 在Android Studio中实现OpenCV人脸检测
- 排序算法学习经验(一)
- vector的实现【C++】
- Python学习笔记2—变量与运算符
- Python基础教程(5)条件、循环和其他语句
- 类、对象、接口
- ASP.NET状态管理之九(会话Session)
- 非零环绕原则
- Kubernetes1.7新特性:支持绕过docker,直接通过containerd管理容器
- hdoj 5532 Almost Sorted Array
- oracle报错: “not a single-group group function”