我创建了一个类并使用多维指针,如下所示:
variable **v_mod;
v_mod = new variable *[3];
for(int i=0;i<3;i++)
{
v_mod[i] = new variable [n];
}
并在使用
后删除指针for( int i = 0 ; i < 3 ; i++ )
{
delete [] v_mod[i];
}
delete [] v_mod;
这工作得非常好,但我使用了很多指针。所以任何人都可以帮助在类中编写一个函数,这有助于创建和删除像
这样的指针variable ** v_mod;
v_mod.create(3,n);
v_mod.delete();
哪种方式相同?
答案 0 :(得分:3)
请勿使用new
使用vector
:
vector<vector<variable>> v_mod(3, vector<variable>(n));
这将要求您的变量对象具有生成的或您自己的默认构造函数。
但除此之外,您可以使用动态分配的数组版本的vector
v_mod
版本,但vector
在超出范围时会自行清理。所以不需要delete
。
修改强>
@Hamza Anis has asked me how to do this without vector
,所以我正在更新此答案以反映几种方法。让我先说一下,vector
是这样做的正确方法,vector
之外的任何东西都只会让处理代码的每个人都变得更加生活。
选项2 unique_ptr
:
unique_ptr<variable[]> v_mod[3];
for(auto& i : v_mod) {
i = make_unique<variable[]>(n);
}
如果选项3是家庭作业,则仅执行此操作:
variable* v_mod[3];
for(auto& i : v_mod) {
i = new variable[n];
}
for(auto& i : v_mod) {
delete[] i;
}