首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在内存中连续分配多维数组的实现

在内存中连续分配多维数组的实现
EN

Stack Overflow用户
提问于 2017-08-25 23:01:48
回答 1查看 46关注 0票数 0

我希望能够在c++中的堆上定义一个通用的多维数组,并希望为该数组分配一个连续的内存,以便快速访问元素(而不是矢量的参差向量)。下面是我的实现

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;

typedef vector<unsigned int> VUI;

class Invalid_MDArray : public exception{
public:
    char* what(){
        return "Array cannot be constructed ";
    }
};

template <class T>
class MArray{
private:
    VUI dsize;
    VUI cumsize;
    T* p;
    unsigned int stot;

public:

    unsigned int size(){ return stot; }
    unsigned int size(unsigned int i) { return dsize[i]; }


    MArray(const VUI& a){


        stot = 1;
        for (unsigned int i = 0; i<a.size(); i++){

            if (a[i] == 0) {
                Invalid_MDArray o;
               throw o;
           }

           stot = stot*a[i];

           dsize.push_back(a[i]);
           cumsize.push_back(stot);
        }

        dsize.push_back(stot);

        p = new T[stot];


    }


    ~MArray(){

        delete[] p;
    }


    inline T& operator()(VUI&& a){

       if (a.size() != dsize.size() - 1) {

            out_of_range o("Index is out of bound!");
            throw o;

       }

       unsigned int i = 0;
       while (i<a.size()){
            if (a[i]>dsize[i] - 1) {

                out_of_range o("Index is out of bound!");
               throw o;
           }
           i++;
        }

        unsigned int index = 0;

        //      index=i+imax*j+imax*jmax*k

       i = 0;
       while (i<a.size()){

            if (i == 0) {
                index = a[i];
            }
            else {
                index = index + a[i] * cumsize[i - 1];

            }


           i++;
        }


       return p[index];
    }

};


int main(){


    try{
        MArray<int>  t({ 2, 2, 2 });
        t({ 1, 1, 1 }) = 10;
        cout << t({ 1, 1, 1 }) << endl;

        // I prefer accessing the elements like this -> cout<<t(1,1,1)<<endl;

        MArray<int>  tt({ 2, 0, 2 }); // OOPS! cannot construct this array!
        cout << t.size()<<endl;
        t({ 1, 2, 1 }) = 1000; //OOPS! outofbound exception!
    }
    catch (exception &e){
        cout << e.what() << endl;
    }

    getchar();
}

但是,我不喜欢用于访问数组的接口,例如

代码语言:javascript
复制
cout << t({ 1, 1, 1 }) << endl;

看起来很丑陋。

有没有可能以不同的方式实现这一点,以便以更自然的方式更好地访问元素,例如cout<<t(1,1,1);

EN

回答 1

Stack Overflow用户

发布于 2017-08-26 01:13:56

我不会重复发明轮子。在谷歌上快速搜索一下,就会发现Boost.MultiArray,这是一个多维数组库,似乎满足了您所有的设计需求。

我还想问一下,这是不是过早的优化。你真的需要更快的速度吗?向量真的很快。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45884305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档