首页 > 代码库 > 类模板MyArray-动态内存

类模板MyArray-动态内存

采用一个动态数组存储数据,有插入,追加,删除,删除元素的功能。

用链表有点浪费空间,用动态数组又增加了delete 和 new的操作。

下面代码采用动态数组的方式。


// 定义一个类模板MyArray,具有求数组长度、插入元素、追加元素、删除元素、查找元素的功能,并在main()加以验证。
#include <iostream>
 
template<typename T>
class MyArray
{
private:
    T *a;
    int len;
public:
    MyArray():a(NULL),len(0){}
    MyArray(int n):len(n){a = new T[n];}
    MyArray(int n,T x):len(n){a = new T[n]; memset(a,x,sizeof(T)*n); }
    ~MyArray(){delete [] a;}
 
    int size() const;
    bool insert(int i,T a);
    bool push_back(T a);
    bool find(T a);
    bool deleteNum(int i);
 
    T & operator[](int i);
    void printall() const;
};
 
template<typename T> 
int MyArray<T>::size() const{
    return len;
}
 
template<typename T> 
bool MyArray<T>::find(T b){
    for(int i=0;i<len;i++)
        if(b == a[i])
            return true;
    return false;
}
 
template<typename T> 
bool MyArray<T>::push_back(T b){
    T *x = new T[len+1];
    if(x == NULL)
        return false;
    for(int i=0;i<len;i++)
        x[i] = a[i];
    x[len] = b;
    delete [] a;
    a = x;
    len++;
    return true;
}
 
template<typename T> 
bool MyArray<T>::insert(int i,T b){
    if(i<0 || i>len)
        return false;
    T *c = new T[len+1];
    if(c == NULL)
        return false;
    int j;
    for(j=0;j<i;j++)
        c[j] = a[j];
    c[j++] = b;
    for(int k=j;k<len+1;k++)
        c[k] = a[k-1];
    delete [] a;
    a = c;
    len++;
    return true;
}
 
template<typename T>
bool MyArray<T>::deleteNum(int i){
    if(i<0||i>=len)
        return false;
    for(int j=i;j<len-1;j++)
        a[j] = a[j+1];
    len--;
    return true;
}
 
template<typename T>
T & MyArray<T>::operator[](int i){
    return a[i];
}
template<typename T>
void MyArray<T>::printall() const{
    for(int i=0;i<len;i++)
        std::cout<<a[i]<<" ";
    std::cout<<"\n";
}
int main()
{
    MyArray<int> a;
    using std::cout;
    using std::endl;
    // add 10,11,14 to array,insert 0 to index 1
    cout<<"add 10,11,14 to array by order,insert 0 to index 1 area:"<<endl;
    a.push_back(10);
    a.push_back(11);
    a.push_back(14);
    a.insert(1,0);
    a.printall();
 
    // find 13, find 14
    if(a.find(13))
        cout<<"13 is in array"<<endl;
    else
        cout<<"13 is not in array"<<endl;
    if(a.find(14))
        cout<<"14 is in array"<<endl;
    else
        cout<<"13 is not in array"<<endl;
 
    // delete some num by index
    cout<<"delete index0 num:"<<endl;
    a.deleteNum(0);
    a.printall();
     
    // get index i num
    cout<<"print the index 1 num"<<endl;
    cout<<a[1]<<endl;
 
    system("pause");
    return 0;
}

类模板MyArray-动态内存