C++day7(异常处理机制、Lambda表达式、类型转换、STL标准库模板、迭代器、list)

cpp 复制代码
#include <iostream>

using namespace std;
template <typename T>
class vector
{
private:
    T* first;
    T* last;
    T* end;
public:
    vector():first(new T),last(first),end(first){cout<<"无参构造"<<endl;}//无参构造
    vector(T* f):first(f),last(f),end(f)//有参构造
    {cout<<"有参构造"<<endl;}
    vector(const vector &other)://拷贝构造
        first(new T[other.end-other.first]),
        last(first+(other.last-other.first)),
        end(first+(other.end-other.first))
    {
        memcpy(this->first,other.first,sizeof(T)*(other.end-other.first));
    }
    vector & operator=(const vector &other)//拷贝赋值都用深拷贝
    {
        if(this!=&other)
        {
            first = new T[other.end-other.first];
            last = first+(other.last-other.first);
            end = first+(other.end-other.first);
            memcpy(this->first,other.first,sizeof(T)*(other.end-other.first));
        }
        return *this;
    }
    T &at(int index)//返回索引的值
    {
        return *(this->first+index);
    }
    bool empty()//判空
    {
        return first==last?true:false;
    }
    T &front()//返回首部元素
    {
        return *this->first;
    }
    T &back()//返回尾部元素
    {
        return *(this->last-1);
    }
    int size()//求元素个数
    {
        return last-first;
    }
    void clear()//清空
    {
        this->last=this->first;
    }
    void expand()//二倍扩容
    {
        T *temp = new T[2*(this->size()*sizeof(T))];

        memcpy(temp,first,sizeof(T)*this->size());
        delete this->first;
        this->first = nullptr;
        this->last = nullptr;
        this->end = nullptr;
        first = temp;
        last = first+sizeof (T)*this->size();
        end = last+sizeof(T)*this->size();
    }
    void push_back(T value)
    {
        *(this->last++) = value;
        if(this->last==this->end)
            this->expand();
    }
    void pop_back()
    {
        this->last--;
    }

};

int main()
{
    vector<int> V;
    V.push_back(1);
    V.push_back(2);
    V.push_back(3);
    V.push_back(4);
    V.push_back(5);
    cout<<V.at(1)<<endl;
    cout<<V.size()<<endl;
    if(V.empty())
    {
        cout<<"空"<<endl;
    }
    else
        cout<<"非空"<<endl;
    cout<<V.back()<<endl;
    cout<<V.front()<<endl;
    V.pop_back();
    V.pop_back();
    for(int i=0;i<V.size();i++)
    {
        cout<<V.at(i)<<" ";
    }
    cout<<endl;
    V.clear();

    return 0;
}
相关推荐
jjkkzzzz4 小时前
Linux下的c/c++开发之操作Redis数据库
数据库·c++·redis
pystraf5 小时前
LG P9844 [ICPC 2021 Nanjing R] Paimon Segment Tree Solution
数据结构·c++·算法·线段树·洛谷
Funny-Boy5 小时前
菱形继承原理
c++
Nobkins7 小时前
2021ICPC四川省赛个人补题ABDHKLM
开发语言·数据结构·c++·算法·图论
海棠蚀omo7 小时前
C++笔记-红黑树
开发语言·c++·笔记
一个Potato8 小时前
C++笔试题(金山科技新未来训练营):
c++·科技
休息一下接着来8 小时前
C++ I/O多路复用
linux·开发语言·c++
龙湾开发8 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 12.曲面细分
c++·笔记·学习·3d·图形渲染
darkchink9 小时前
[LevelDB]LevelDB版本管理的黑魔法-为什么能在不锁表的情况下管理数据?
c语言·数据库·c++·oracle·数据库开发·dba·db
易只轻松熊9 小时前
C++(23):容器类<vector>
开发语言·数据结构·c++