简单vector
- #include
- #include
- using namespace std;
-
- template <typename T>
- class myvector{
- private:
- T *first;
- T *last;
- T *end;
- public:
- //无参构造
- myvector(){
- first = new T[1];
- last = first;
- end = first+1;
- }
-
- //有参构造
- myvector(int num,const T &val){
- first = new T[num + 1];
- last = first;
- end = first + num;
- for(int i=0;i
- first[i] = val;
- last++;
- }
- }
-
- //拷贝构造
- myvector(const myvector
*other){ - int len = other->end - other->first+1;
- this->first = new T[len];
- this->last = other->last;
- this->end = other->end;
- for(int i=0;i
-1;i++){ -
- this->first[i] = other->first[i];
- ++last;
- }
- end += len-1;
- }
-
- //拷贝赋值
- myvector &operator = (const myvector
*other){ - if(this!=&other){
- delete []first;
- int len = other->end - other->first+1;
- this->first = new T[len];
- this->last = other->last;
- this->end = other->end;
- for(int i=0;i
-1;i++){ -
- this->first[i] = other->first[i];
- }
- }
- return *this;
- }
-
- //析构函数
- ~myvector(){
- delete []first;
- first = nullptr;
- last = nullptr;
- end = nullptr;
- }
-
- //判空
- bool empty(){
- if(last == first)
- return true;
- else
- return false;
- }
-
- //判满
- bool full(){
- return last == end;
- }
-
- //尾插
- void push_back(const T &val){
- if(full())
- expand();
- *last = val;
- last++;
- }
-
- //尾删
- void pop_back(){
- if(empty()){
- throw -1;
- }
- last--;
- }
-
- //二倍镜扩容
- void expand(){
- int t = last-first;
- T *temp = new T[2*(end-first)];
- for(int i=0;i
- temp[i] = first[i];
- }
- delete []first;
- first = temp;
- last = first+t;
- end = first + 2*(end-first);
- temp = nullptr;
- }
-
- //at函数
- T &at(int pos){
- if(pos<0||pos>end-first){
- throw -1;
- }
- return first[pos];
- }
-
- //返回首元素
- T &front(){
- return *first;
- }
-
- //返回尾元素
- T &back(){
- return *(end-1);
- }
-
- //求元素个数
- int size()const{
- return last-first;
- }
-
- //清空
- void clear(){
- last = first;
- }
-
- //遍历
- void show(){
- for(int i=0;i<size();i++){
- cout<
" "; - }
- cout<
- }
-
- };
-
- int main()
- {
- myvector<int> v1(4,8);
- v1.show();
- v1.push_back(5);
- v1.show();
- myvector<int> v2(v1);
- cout<<"v2长度为"<
size()< - v2.pop_back();
- cout<<"尾删后v2长度为"<
size()< - v2.clear();
- cout<<"清空后v2长度为"<
size()< -
- return 0;
- }
-
相关阅读:
GoLong的学习之路(二十一)进阶,语法之并发(go最重要的特点)(协程的主要用法)
【每日一题】2304. 网格中的最小路径代价-2023.11.22
Springboot利用Security做OAuth2授权验证
Java CC 解析 SQL 语法示例
Numpy(二) 元素与数组的操作
听GPT 讲Rust源代码--library/std(15)
Sass 基础教程——预处理器
Git 详细安装教程
【论文阅读】Dense Passage Retrieval for Open-Domain Question Answering
【生成式网络】入门篇(五):Pix2Pix 的 代码和结果记录
-
原文地址:https://blog.csdn.net/2301_77665369/article/details/132890995