【问题标题】:How to properly delete multidemensional vector? [duplicate]如何正确删除多维向量? [复制]
【发布时间】:2014-04-17 06:55:38
【问题描述】:

所以我在下面创建两个不同的多维向量

string **customdiceArray = new string*[crows];
for(unsigned int i = 0; i<crows;i++){
    customdiceArray[i] = new string[ccolumns];
}

然而,他们给了我内存泄漏。我对两个向量都进行了如下所示的删除调用。我哪里错了?

//Deallocate create objects
delete diceArray;
diceArray = 0;

//set<string>* words = new set<string>;
delete words;
words = 0;

//string **customdiceArray = new string*[crows];
delete customdiceArray;
customdiceArray = 0;

【问题讨论】:

  • 这些是数组。不是向量。
  • 你必须遍历数组删除每个元素,然后删除数组。
  • 像这样:std::vector&lt;std::vector&lt;std::string&gt;&gt; dice(crows, std::vector&lt;std::string&gt;(ccolumns));
  • 好的 C++ 程序几乎不包含 delete 语句。如果您实际上使用 vector 而不是数组,您的代码会更简单和正确。

标签: c++ vector multidimensional-array memory-leaks


【解决方案1】:

因此,如果您想在此处以适当的方式使用删除,请举一些例子:

对于一个变量

string *i = new string;
delete i;

对于数组(一维)

string *i = new string[10];
delete[] i;

对于数组(多维)

string **i = new *string[10]
for(int j=0; j<10;++j){
   i[j] = new string[10];
}

for(int j=0; j<10;++j){
   delete[] i[j];
}
delete[] i;

【讨论】:

  • 非常感谢阿德尔。这解决了我的内存泄漏问题!
【解决方案2】:

为避免内存泄漏和编写 C++ 原生代码,您还可以使用 std::vector 代替需要更多注意和维护的 C 数组。

例如:

vector<vector<int> > matrix;

vector<int> cols;
cols.push_back(1);
cols.push_back(2);
cols.push_back(3);

matrix.push_back(cols);
matrix.push_back(cols);

for(int i=0; i<matrix.size(); i++)
  for(int j=0; j<cols.size(); j++)
    cout << matrix[i][j] << endl;

结果:

1
2
3
1
2
3

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 2023-03-04
    • 1970-01-01
    • 2021-06-12
    • 2012-11-14
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多