关闭

数组类模板

277人阅读 评论(0) 收藏 举报

问题及描述;

/*
 *Copyright (c) 2016,烟台大学计算机学院
 *All rights reserved.
 *文件名称;test.cpp
 *作者;邱凯
 *完成日期;2016年5月31号
 *版本号;v6.0
 *问题描述;  数组类模板
 *输入描述;  输入数据
 *输出描述; 输出答案
*/
#include <iostream>
#include <iomanip>
#include <cassert>
using namespace std;

template <class T>
class Array
{
private:
    T* list;
    int size;
public:
    Array(int sz = 50);
    Array(const Array<T> &a);
    ~Array();
    Array<T> & operator = (const Array<T> &rhs);
    T & operator [] (int i);
    const T & operator [] (int i) const;
    operator T * ();
    operator const T * () const;
    int getSize() const;
    void resize(int sz);
};

template <class T> Array<T>::Array(int sz)
{
    assert(sz >= 0);
    size = sz;
    list = new T [size];
}

template <class T> Array<T>::~Array()
{
    delete [] list;
}


template <class T> Array<T>::Array(const Array<T> &a)
{
    size = a.size;

    list = new T[size];
    for (int i = 0; i < size; i++)
        list[i] = a.list[i];
}


template <class T>
Array<T> &Array<T>::operator = (const Array<T>& rhs)
{
    if (&rhs != this)
    {

        if (size != rhs.size)
        {
            delete [] list;
            size = rhs.size;
            list = new T[size];
        }

        for (int i = 0; i < size; i++)
            list[i] = rhs.list[i];
    }
    return *this;
}


template <class T>
T &Array<T>::operator[] (int n)
{
    assert(n >= 0 && n < size);
    return list[n];
}

template <class T>
const T &Array<T>::operator[] (int n) const
{
    assert(n >= 0 && n < size);
    return list[n];
}


template <class T>
Array<T>::operator T * ()
{
    return list;
}

template <class T>
Array<T>::operator const T * () const
{
    return list;
}


template <class T>
int Array<T>::getSize() const
{
    return size;
}


template <class T>
void Array<T>::resize(int sz)
{
    assert(sz >= 0);
    if (sz == size)
        return;
    T* newList = new T [sz];
    int n = (sz < size) ? sz : size;

    for (int i = 0; i < n; i++)
        newList[i] = list[i];
    delete[] list;
    list = newList;
    size = sz;
}
int main()
{
    Array<int> a(10);
    int n, count = 0;
    cout << "Enter a value >= 2 as upper limit for prime numbers: ";
    cin >> n;
    for (int i = 2; i <= n; i++)
    {
        bool isPrime = true;
        for (int j = 0; j < count; j++)
            if (i % a[j] == 0)
            {
                isPrime = false;
                break;
            }
        if (isPrime)
        {
            if (count == a.getSize()) a.resize(count * 2);
            a[count++] = i;
        }
    }
    for (int i = 0; i < count; i++)
        cout << setw(8) << a[i];
    cout << endl;
    return 0;
}

运行结果;


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16198次
    • 积分:1030
    • 等级:
    • 排名:千里之外
    • 原创:91篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    最新评论