2013-05-10 72 views
-4

我到2-d陣列分配存貯器進行,我知道的深度分配內存的2-d陣列

int *array[size]; 
for(int i=0;;i++) 
{ 
    array[i]=new int[10]; 
} 

我這樣做對嗎?

+0

爲什麼不乾脆把它包在一個具有'at'算子的對象,像一個載體有哪些?這樣你就不必在你的代碼中使用矩陣aritmetiks。 – 2013-05-10 21:01:50

回答

1

不,您需要for(int i=0; i<size; i++)以便循環僅執行size次。但這並不是最優雅的方式。在C++中,建議我們使用STL vector!而非陣列以避免內存管理:

vector<vector<int> > array; 

Using arrays or std::vectors in C++, what's the performance gap?

+0

其餘的都好嗎? – user1838070 2013-05-10 20:36:40

+0

是的,其餘的都沒問題。 – Yang 2013-05-10 20:38:01

+0

@ user1838070,那麼,你應該考慮切換到爲你管理內存的東西,比如'std :: vector'。 – chris 2013-05-10 20:38:31

0

你真的不應該以這種方式實現矩陣 - 真的。除非尺寸變化,請不要。

一個更好的辦法是:

template<typename Ty> 
class matrix { 
public: 
    const unsigned dim_x, dim_y; 

private: 
    Ty* const data; 

public: 
    matrix(const unsigned dim_x, const unsigned dim_y) 
    : dim_x(dim_x), dim_y(dim_y), data(new Ty[dim_x *dim_y]) 
    {} 

    ~matrix() { 
    delete[] data; 
    } 

    const Ty at(unsigned i, unsigned j) const { 
    return data[i + j*dim_x]; 
    } 

    Ty& at(unsigned i, unsigned j) { 
    return data[i + j*dim_x]; 
    } 
}; 

然後就是與基體類訪問數據。

我寫了一個博客帖子我啄一下吧here