2012-10-10 76 views
6

我必須在不知道大小的情況下聲明一個數組或數組的多維數組。 我想要做類似我在這個情況下做簡單的數組的東西:C++聲明不知道大小的數組數組

int *array; 
cin >> size; 
array = new int[size]; 

也許我可以做一個循環來初始化指針這樣的指針:

int **array; 
cin >> rows >> col; 
array = new *int[rows] 
for (int i = 0; i < rows; ++i) 
    array[i] = new int[col]; 

但我更喜歡唐如果有更好的解決方案是可能的,就不要這樣做。

+0

如果你想只在運行時已知大小的數組,你可能真正需要的是一個'的std :: VECTOR'。 – cHao

+1

你瞭解了標準庫嗎?你知道一個'std :: vector'是什麼嗎? – amdn

+0

@PuraVida我非常瞭解標準庫謝謝。 我正在測試使用矢量>和數組int [] []的性能,所以我需要使用該數組,因此我不想使用循環來初始化它。 –

回答

5

爲什麼不使用std :: vector?

std::vector<std::vector<int> > array; 

如果你不希望使用指針數組,你可以使用你動態地分配你的規模和訪問它行的一組後的一個大陣。

int rows = 10; 
int columns = 20; 

int* array = new int[rows * columns]; 

for (int count = 0; count < rows; count++) 
{ 
    int* row = &array[count * columns]; 

    for (int inner_count = 0; inner_count < columns; inner_count++) 
    { 
     int* element = &row[inner_count]; 

     //do something 
    } 
} 

delete [] array; 
+2

如果有問題的代碼是性能敏感的,不要使用'vectors'的'vector'。與單個大塊內存相比,您將面臨大量的緩存未命中。 –

+0

@ EdS.yea這是原因之一,我想嘗試這樣做,而不使用循環來初始化它。 –

1

你幾乎不得不去使用循環版本。你可以讓一個略有改善,這是分配了一個大的塊,然後建立自己的int*索引到它:

int **array; 
int *storage; 
cin >> rows >> col; 
array = new *int[rows]; 
storage = new int[rows*col]; 
for (int i = 0; i < rows; ++i) 
    array[i] = storage + col * i; 

這有你仍然可以使用array[i][j]語法訪問數組很好的特性。

0

如果你願意,你可以有更多的一點點方便由具有助手

template <typename T> 
struct C3DArray 
{ 
    vector<vector<vector<T>>> m; 
    C3DArray(int size_x, int size_y, int size_z) 
     : m(make(T(), size_z, size_y, size_x)) 
    { } 

    template <typename U> static std::vector<U> make(U v, size_t n) { 
     return { n, std::move(v) }; 
    } 

    template <typename U, typename... Dim> static auto make(U v, size_t n, Dim... other) 
     -> std::vector<decltype(make(v, other...))> { 
     return { n, make(v, other...) }; 
    } 
}; 

這使用variadics。使用這樣的:

C3DArray<int> arr(3,4,20); 
0

你可以使用一個單一的std ::向量包含整個二維數組,敷在一類隱藏的細節。下面是一個示例,它使用data(row, col)成員函數,該函數返回對rowcol處元素的引用。我包含了一個示例2維矩陣int,其中陣列中的每個條目都被初始化爲其產品rowcol。當這個類的一個實例超出作用域時,默認的析構函數會被調用並釋放內存,這樣你就不必記得調用delete []來釋放內存。矩陣的所有元素在內存中都是連續的,這對緩存很友好,並且應該給你提供良好的性能。

#include <iostream> 
#include <vector> 
#include <stdexcept> 

template <typename T> 
class matrix { 
    std::vector<T> data_; 
public: 
    size_t const rows_; 
    size_t const cols_; 
    matrix(size_t rows, size_t cols) 
     : rows_(rows) 
     , cols_(cols) 
     , data_(rows * cols) 
    {} 
    T& data(size_t row, size_t col) { 
     if (row > rows_ || col > cols_) throw std::out_of_range("matrix"); 
     return data_[ row * cols_ + col ]; 
    } 
}; 

int main(int argc, char** argv) 
{ 
    matrix<int> array(100,100); 

    for(size_t r=0; r < array.rows_; ++r) { 
     for(size_t c=0; c < array.cols_; ++c) { 
      array.data(r,c) = r * c; 
     } 
    } 

    std::cout << "8 x 7 = " << array.data(8,7) << std::endl; 

    return 0; // array goes out of scope here, memory released automatically 
} 

當你運行這個你會得到

8 x 7 = 56 
+0

感謝您的解釋,我會試試這個 –