2016-07-15 24 views
1

如何使用new运算符编写以下代码? 请详细解释。 在此先感谢。将malloc转换为新的

#include<alloc> 
#define MAXROW 3 
#define MAXCOL 5 
using namespace std; 

int main() 
{ 
    int (*p)[MAXCOL]; 
    p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p)); 
} 
+0

请注意''不是标准标题。对于'malloc',使用''。 – chris

回答

2

很简单,回答字面上的问题:

p = new int[MAXROW][MAXCOL]; 

此分配的自由存储区和一个二维数组(由MAXCOL MaxRow的),像往常一样new,返回int(*)[MAXCOL] - 与衰减2D阵列相同的类型。别忘了delete[] p;

最后一部分提出了std::vector的重要性。据推测,你在编译时知道第二维的大小。因此,std::vector<std::array<int, MAXCOL>>将与不需要delete[]声明的额外奖励一起使用,并知道其大小(MAXROW)。如果可能的话请使用这个。

事实上,在你的例子中,两个维度在编译时已知,这意味着std::array<std::array<int, MAXCOL>, MAXROW>也可以在这里工作。这通常比动态分配更可取。

如果在编译时都不知道维度,那么当您知道每个内部向量的大小相同时,您最好的选择通常是向量或专用矩阵类的向量来提高性能。

1

字面问题

如何编写使用new运算符下面的代码?

&hellip;意味着别的东西比你认为的意思。

new操作者是一个简单分配的功能大致直接类似于C中的malloc,除C++ new操作者是可更换的由用户定义的一个。

您可能的意思是new表达式。这样的表达式调用new运算符进行分配,然后然后调用构造函数进行初始化,如果分配的东西是类类型的话。它是安全的。

尽管如此,对于你的阵列,你也不想那么做,只是从标准库中只需要std::vector


下面是使用向量的std::vector创建一个矩阵的例子:

#include <vector> 
using namespace std; 

auto main() 
    -> int 
{ 
    int const n_rows = 3; 
    int const n_cols = 5; 

    using Row = vector<int>; 

    vector<Row> v(n_rows, Row(n_cols)); 

    // E.g. v[1] is a row, and v[1][2] is an int item in that row. 
} 

即使你不经常使用的矩阵,它可以是包裹是一个好主意矩阵的一般概念,在一个类中。一种简单的方法是使用单个std::vector进行存储,并提供例如一个at函数或一个operator()从客户端代码索引。如果您还不想自己做这个,那么例如Boost库提供了一个矩阵类。

+0

通常,我避免使用像对象一样的N-dim数组的嵌套向量。有多个indirections访问一个元素会减慢速度。 – doug

+0

@doug:我同意。这就是为什么我建议使用单个矢量作为矩阵存储。简单的声明是嵌套的原因。 (顺便说一下,我发现没有人对明显的错字发表评论,这真是太神奇了:)修正:) :) –

+0

有一种非常简单的方法来使用单个向量,并仍然使用数组中的2D语义。 (http://stackoverflow.com/questions/36123452/statically-declared-2-d-array-c-as-data-member-of-a-class/36123944#36123944) – doug

1

由于这是C++,我会建议更换使用std::array和使用malloc时,你应该使用free未页头或释放内存,如果使用new你需要使用deletestd::unique_ptr 也;如果你new[]你需要使用delete[]

#include <cstdlib> 
#include <memory> 
#include <array> 
#define MAXROW 3 
#define MAXCOL 5 
using namespace std; 

int main() 
{ 
    int (*p)[MAXCOL]; 
    p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p)); 
    free(p); //free memory 
    array<int,MAXCOL> *p1 = new array<int,MAXCOL>[MAXROW]; 
    delete []p1; //use this to delete the variable 
    array<array<int,MAXCOL>,MAXROW> *p2 = new array<array<int,MAXCOL>,MAXROW>; 
    delete p2; // normal delete for this one 
    auto p3 = make_unique<array<array<int,MAXCOL>,MAXROW>>(); 
    //no delete needed for p3, it is a smart pointer. 
}