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;
}
相关推荐
2401_891482172 小时前
多平台UI框架C++开发
开发语言·c++·算法
无敌昊哥战神2 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
Darkwanderor3 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920743 小时前
分布式系统安全通信
开发语言·c++·算法
2401_877274244 小时前
从匿名管道到 Master-Slave 进程池:Linux 进程间通信深度实践
linux·服务器·c++
汉克老师4 小时前
GESP5级C++考试语法知识(八、链表(三)循环链表)
c++·约瑟夫问题·循环链表·gesp5级·gesp五级
阿贵---4 小时前
C++中的RAII技术深入
开发语言·c++·算法
PiKaMouse.5 小时前
navigation2-humble从零带读笔记第一篇:nav2_core
c++·算法·机器人
lightqjx5 小时前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
Irissgwe6 小时前
进程间通信
linux·服务器·网络·c++·进程间通信