二维变长数组

/*
 * 数组内元素的位置是不变的,只是数组容量的大小发生了变化。
 * 简单来说,就是将数组的左上角元素平移到新数组的相同位置。
 * 
*/
template<class T>
void changeLength2D(T**& a,int oldRows
                     int copyRows,int copyColumns,
                     int newRows,int newColumns)
{
    if(copyRows > newRows || copyColumns > newColumns)
        throw illegalParameterValue("new dimensions are too small");

    T** temp = new T*[newRows];
    for(int i = 0;i < newRows;i++)
        temp[i] = new T[newColumns];

    //将元素从旧空间迁移到新空间,并释放旧空间
    for(int i = 0;i< copyColumns;i++)
    {
        copy(a[i],a[i]+copyColumns,temp[i]);
        delete [] a[i];
    }

    for(int i = copyRows;i< oldRows;i++)
        delete [] a[i];

    delete [] a;
    a = temp;
}

猜你喜欢

转载自my.oschina.net/u/1771419/blog/1799510