4月25日 QT

#include <iostream>
#include <cstring>
 
 
using namespace std;
 
 
#define ERROR "通常错误"
 
 
 
 
 
 
 
 
template<typename T>
class Vector
{
  
  
public:
    Vector();
    Vector(int num, T data);    //使用num个data初始化
    Vector(Vector &other);
    ~Vector();
 
 
 
 
    T &at(int pos);
    bool empty();
    bool full();
    T &front();
    T &back();
    int size();
    void clear();
    void expand();
 
 
 
 
private:
    T *begin;   //表首
    T *end;     //数据尾部后一位, 方便填充新数据
    T *last;    //容器结尾
 
 
};
 
 
//无参构造
template<typename T>
Vector<T>::Vector(): begin(nullptr), end(nullptr), last(nullptr)
{
  
  
    cout << "无参析构" << endl;
}
 
 
//有参构造
template<typename T>
Vector<T>::Vector(int num, T data): begin(new T[num])
{
  
  
    if (num < 0)
    {
  
  
        throw ERROR;
    }
 
 
    //容量为2的倍数
    int size = 1;
    while (size < num) {
  
  
        size *= 2;
    }
    memset(begin, 0, size);
 
 
    end = begin + size;
    last = begin + num -1;
 
 
    T *temp = begin;
    for (int i=0 ; i<num ; i++)
    {
  
  
        *temp = data;
        temp ++;
    }
    cout << "有参析构" << endl;
}
 
 
//拷贝构造
template<typename T>
Vector<T>::Vector(Vector &other)
{
  
  
    if (this != &other)
    {
  
  
        int size = other.last - other.begin +1;
        this->begin = new T[size];
        this->last = this->begin + size -1;
        this->end = this->begin + (other.end - other.begin);
 
 
        memcpy(this->begin, other.begin, size);
    }
 
 
    cout << "拷贝构造" << endl;
}
 
 
//析构函数
template<typename T>
Vector<T>::~Vector()
{
  
  
    delete [] this->begin;
    begin = nullptr;
    end = nullptr;
    last = nullptr;
    cout << "析构函数" << endl;
}
 
 
 
 
template<typename T>
T &Vector<T>::at(int pos)
{
  
  
    if (pos < 0 || pos > (this->begin - this->last + 1))
    {
  
  
        cout << "越界" << endl;
        return NULL;
    }
 
 
    return *(begin+pos);
}
 
 
 
 
template<typename T>
bool Vector<T>::empty()
{
  
  
    return this->begin == this->last;
}
 
 
template<typename T>
bool Vector<T>::full()
{
  
  
    return (this->begin - this->last) == (this->begin - this->end);
}
 
 
template<typename T>
T &Vector<T>::front()
{
  
  
    return *this->begin;
}
 
 
 
 
template<typename T>
T &Vector<T>::back()
{
  
  
    return *(this->end);
}
 
 
template<typename T>
int Vector<T>::size()
{
  
  
    return this->end - this->begin;
}
 
 
template<typename T>
void Vector<T>::clear()
{
  
  
    memset(this->begin, 0, (this->last - this->begin));
}
 
 
 
 
 
 
 
 
 
 
 
 
int main()
{
  
  
    cout << "Hello World!" << endl;
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/weixin_73148834/article/details/130374685
qt4
今日推荐