[英]c++ two dimensional array question
我想創建一個指向二維指針數組的指針(具有x
的寬度和高度)。
這段代碼會達到我的預期嗎? (創建數組元素,寫出一些關於它們的信息,然后釋放所有分配的memory。)
int main(int argc, char** argv) {
int x = 3;
Node ***array = new Node**[x];
for (int i = 0; i < 3; i++) {
array[i] = new Node*[x];
for (int j = 0; j < x; j++) {
array[i][j] = new Node(i, j); /* Node::Node(int row, int col) */
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
cout << array[i][j]->row << ", " << array[i][j]->col << endl;
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
delete array[i][j];
//array[i][j] = NULL;
}
delete[] array[i];
//array[i] = NULL;
}
delete[] array;
//array = NULL;
return 0;
}
或者我應該創建一個指向Node
對象的指針vector
vector
?
或者我應該在堆棧上分配我的對象嗎?
(我使用的是指針,因為在 Java 或 C# 中,創建 object 時必須始終使用new
關鍵字(但是,我不認為內存中有更多對象)堆上的可用空間。)
我使用帶有new
關鍵字的指針的另一個原因是,我想創建多個指向同一個 object 的指針。 我應該在堆棧上創建一個 object,然后只創建指向該 object 的指針嗎?
我建議您使用vector< vector<Node> >
, boost::multi_array ,或者您可以匯總您自己的動態二維數組 class (這並不難),它是一個平面一維std::vector
的包裝器。
上述所有解決方案都將您的 Node 對象存儲在堆中,並負責清理 memory。
這是一個簡單的矩陣 class 的示例,它是std::vector<T>
的包裝器:
#include <iostream>
#include <vector>
template <class T>
class Matrix
{
public:
Matrix() : width_(0), height_(0), vec_(0) {}
Matrix(size_t width, size_t height)
: width_(width), height_(height), vec_(width*height) {}
size_t size() const {return vec_.size();}
size_t width() const {return width_;}
size_t height() const {return height_;}
// Clears all preexisting data
void resize(size_t width, size_t height)
{width_ = 0; height_ = 0; vec_.clear(); vec_.resize(width*height);}
void clear() {width_ = 0; height_ = 0; vec_.clear();}
T& operator()(size_t col, size_t row) {return vec_[row*width_ + col];}
const T& operator()(size_t col, size_t row) const
{return vec_[row*width_ + col];}
private:
size_t width_;
size_t height_;
std::vector<T> vec_;
};
int main()
{
Matrix<double> a(3, 4);
a(1, 2) = 3.1415;
std::cout << a(1,2) << "\n";
}
它使用operator()
來模仿 c 風格多維 arrays 的array[2][4]
語法。 您不必擔心淺拷貝、釋放 memory 等,因為vector
已經解決了這些問題。
您是否考慮過使用Boost.Multidimensional.Array
?
它看起來可以充分解決您要解決的問題。 如果您的問題可以接受,您可以將它與Node*
或實際的Node
類型一起使用。
您的代碼看起來是正確的,但我建議您創建Node
對象的向量向量。 vector
class 管理自己的 memory,因此您永遠不必擔心忘記delete
任何內容。
您甚至不必將其設為Node
指針向量的向量。 如果你說my_vector.push_back(my_node)
,它my_node
復制到向量的堆分配 memory 中。 如果您從 function 返回向量,則該節點隨之而來(它不會在 function 的末尾丟失,就像堆棧分配的對象一樣)。 例如:
// declare a vector of nodes on the stack
vector<node> nodes;
// declare a Node object on the stack
Node my_node(/*arguments*/);
// copy my_node (on the stack) into the vector's memory (on the heap)
nodes.push_back(my_node);
// (return 'nodes' from this function and store it somewhere)
請注意,節點中的nodes
與 my_node 是不同的my_node
。 如果您使用new
創建 my_node , push_back()
將復制指針(不是 object 本身),並且向量中的 object 將與您使用new
創建的相同。 如果你這樣做,你就擁有了 object,你必須記住在完成后刪除它。 如果您讓向量擁有 object(如我的代碼示例中所示),它將為您處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.