现在的位置: 首页 > 综合 > 正文

C++实战:一个轻型数组类的实现

2012年12月01日 ⁄ 综合 ⁄ 共 2505字 ⁄ 字号 评论关闭

C++实战:一个轻型数组类的实现

说明:这个数组类可视为标准库中vector的简化版:支持数组的一般操作,支持复制、赋值,支持重新定义大小; 不考虑多线程,不考虑预分配额外空间以进行的性能优化,不设置迭代器。

#include <iostream>                 // 仅用于测试时输出,数组类本身不需要

template <typename Type>
class Array
{
public:
    typedef unsigned int size_tp;   // 数组的尺寸(下标)类型

    Array(size_tp size = 0, Type t = Type());     // 可以用size指定初始大小,t指定初始值
    Array(const Array& array);
    ~Array();                                     // 空间自动释放

    Type& operator[](size_tp index);              // 下标访问(读/写形式)
    const Type& operator[](size_tp index) const;  // 下标访问(只读形式)
    Array& operator=(const Array& rhs);           // 赋值,改变大小/内容

    size_tp get_size() const;                     // 获得数组大小
    void resize(size_tp size);                    // 重设数组大小,若改小,则丢弃尾数据

    void push_back(const Type& value);            // 追加一个数组元素,数组大小增一

private:
    void copy(const Type *p_source, Type *p_target, size_tp size);
    size_tp _size;
    Type *_arr;
};

template <typename Type>
Array<Type>::Array(size_tp size, Type t): _size(size), _arr(size ? new Type[size] : 0)
{
    for (size_tp i = 0; i < size; ++i)      // not executed if (size == 0)
 _arr[i] = t;
}

template <typename Type>
Array<Type>::Array(const Array& array):
_size(array._size),
_arr(array._size ? new Type[array._size] : 0)
{
    copy(_array._arr, _arr, array._size);  // do nothing if (array._size == 0)
}

template <typename Type>
Array<Type>::~Array()
{
    delete[] _arr;
}

template <typename Type>
Array<Type>& Array<Type>::operator=(const Array<Type>& rhs)
{
    if (&rhs != this)
    {
 resize(rhs._size);
 copy(rhs._arr, _arr, _size);
    }
    return *this;
}

template <typename Type>
Type& Array<Type>::operator[](size_tp index)
{
    if (index >= _size)
 throw("Array::out of range");
    return _arr[index];
}

template <typename Type>
const Type& Array<Type>::operator[](size_tp index) const
{
    if (index >= _size)
 throw("Array::out of range");
    return _arr[index];
}

template <typename Type>
Array<Type>::size_tp Array<Type>::get_size() const
{
    return _size;
}

template <typename Type>
void Array<Type>::copy(const Type *p_source, Type *p_target, size_tp size)
{
    for (size_tp i = 0; i < size; ++i)      // not executed if (size == 0)
 p_target[i] = p_source[i];
}

template <typename Type>
void Array<Type>::resize(size_tp new_size)
{
    if (new_size)
    {
 Type *p = new Type[new_size];
 copy(_arr, p, _size < new_size ? _size : new_size);
 delete[] _arr;
 _arr = p;
    }
    else
    {
 delete[] _arr;
 _arr = 0;
    }
    _size = new_size;
}

template <typename Type>
void Array<Type>::push_back(const Type& value)
{
    resize(_size + 1);
    _arr[_size - 1] = value;
}

int main()                 // 主测试函数
{
    Array<int> a(30, 5);
    Array<int> b;
    b.push_back(20);
    b.push_back(100);
    a = b;
    for (Array<int>::size_tp i = 0; i < a.get_size(); ++i)
 std::cout << a[i] << std::endl;
    return 0;
}

抱歉!评论已关闭.