荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: Version (Who makes history and why), 信区: Program
标  题:  动态二维三维数组
发信站: 荔园晨风BBS站 (Tue Mar 25 18:43:33 2003), 站内信件


#include <stdio.h>
#include <malloc.h>

// pre-declaration
template < class T, bool bInternal > class Array3;

// template class Array2
template <class T, bool bInternal=false>
class Array2 {
public:
    typedef Array2<T, bInternal> _Myt;
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T& reference;
    typedef const T& const_reference;

    Array2(int x, int y) : a(x), b(y) {
        data = (pointer)malloc(sizeof(value_type)*x*y);
    }
    ~Array2() {
        if(!bInternal)
            free(data);
    }
    pointer operator [] (int i) {
        ASSERT(i>= 0 && i < a);
        return data + i * b;
    }
    const_pointer operator [] (int i) const {
        ASSERT(i>= 0 && i < a);
        return data + i * b;
    }
protected:
    // used in template class Array3
    Array2(value_type* ptr, int x, int y) : data(ptr), a(x), b(y) {
    };

    pointer data;
    int     a, b;

    friend  Array3<T, true>;
    friend  Array3<T, false>;
};

// template class Array3
template <class T, bool bInternal=false>
class Array3 {
public:
    typedef Array3<T, bInternal> _Myt;
    typedef Array2<T, true> a2type;
    typedef const Array2<T, true> const_a2type;
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T& reference;
    typedef const T& const_reference;

    Array3(int x, int y, int z) : a(x), b(y), c(z) {
        data = (pointer)malloc(sizeof(value_type)*x*y*z);
    }
    ~Array3() {
        if(!bInternal)
            free(data);
    }
    a2type operator [] (int i) {
        ASSERT(i>= 0 && i < a);
        return a2type(data + i * b * c, b, c);
    }
    const_a2type operator [] (int i) const {
        ASSERT(i>= 0 && i < a);
        return a2type(data + i * b * c, b, c);
    }
protected:
    // used in template class Array4
    Array3(value_type* ptr, int x, int y, int z) : data(ptr), a(x),
        b(y), c(z) {
    };

    pointer data;
    int     a, b, c;
};

int main(int argc, char* argv[])
{
    Array3<int> a3(4, 3, 2);
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<3;j++)
        {
            for(int k=0;k<2;k++)
            {
                printf("&a[%d][%d][%d] = %p\n", i, j, k, &a3[i][j][k]);

            }
        }
    }
    return 0;
}

还不是很完善

照样子也容易写出动态的四维数组实现,不过可能实际意义不大

如果需要,自己照葫芦画瓢吧,反正不难

--

--
                      *
          *                                  *
                          *             *
                      no more to say
                  ★     just wish you   ★
                            good luck

※ 来源:·荔园晨风BBS站 bbs.szu.edu.cn·[FROM: 192.168.1.50]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店