C++模板类实现顺序表

时间:2023-01-02 19:51:43
#pragma once

#include<stdio.h>
#include <iostream>
#include<string>
#include<assert.h>
using namespace std;


template <class T>
class Vector
{
public:
    Vector()
        : _a(NULL)
        , _size(0)
        , _capacity(0)
    {}

    ~Vector()
    {
        if (_a)
        {
            delete []_a;
            _a = NULL;
            _capacity = _size = 0;
        }
    }
    void Pushback(const T& x)//尾插
    {
        _CheckCapacity();

        _a[_size] = x;
        ++_size;
    }
    void Popback()//尾删
    {
        if (_size == 0)
        {
            return;
        }
        else
        {
            --_size;
        }
    }
    void PushFront(const T& x)//头插
    {
        _CheckCapacity();
        if (_size == 0)
        {
            ++_size;
            _a[0] = x;
        }
        else
        {
            for (size_t i = _size; i > 0; i--)
            {
                _a[i] = _a[i - 1];
            }
            _a[0] = x;
            ++_size;
        }
    }

    void PopFront()
    {
        if (_size == 0)
        {
            return;
        }
        else
        {
            for (size_t i = 0; i < _1size; i++)
            {
                _a[i] = _a[i + 1];
            }
            --_size;
        }
    }
    int Find(const T& x)
    {
        for (size_t i = 0; i < _size; i++)
        {
            if (_a[i] == x)
            {
                return i;
            }
        }
        return -1;
    }
    void insert(size_t pos, const T& x)//在任意位置前面插入一个元素
    {
        assert((pos >= 0) && (pos < _size));
        _CheckCapacity();
        for (size_t i = _size; i > pos; i--)
        {
                _a[i] = _a[i - 1];
        }
        _a[pos] = x;
        _size++;

    }

    void Erase(size_t pos)
    {
        assert((pos >= 0) && (pos < _size));
        for (size_t i = pos; i < _size; i++)
        {
            _a[i] = _a[i + 1];
        }
        --_size;
    }
    void Print()
    {
        for (size_t i = 0; i < _size; i++)
        {
            cout << _a[i] << " ";
        }
    }
protected:
    void _CheckCapacity()
    {
        if (_size>=_capacity)
        {
            size_t newCapacity = _capacity * 2 + 3;
            T *tmp = new T[newCapacity];//new除了开辟这么多空间,还会调用T的构造函数对其初始化
            if (_a)
            {
                /*memcpy(tmp, _a, sizeof(T)*_size); delete[] _a;*/
                for (size_t i = 0; i < _size; ++i)
                {
                    tmp[i] = _a[i];
                }
            }
            _capacity = newCapacity;
            _a = tmp;
        }
    }
protected:
    T *_a;
    size_t _size;
    size_t _capacity;
};

测试代码如下:

void TestVector1()
{
    Vector<int> V1;
    V1.Pushback(1);
    V1.Pushback(2);
    V1.Pushback(3);
    V1.Erase(2);
    V1.Print();
}