在C ++中声明和分配2D数组 [英] Declaring and allocating a 2d array in C++

查看:81
本文介绍了在C ++中声明和分配2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Fortran用户,对C ++不够了解.我需要对现有的C ++代码进行一些补充.我需要创建一个类型为double的2d矩阵(例如A),其大小(例如m x n)仅在运行期间才知道.使用Fortran可以按以下步骤完成

I am a Fortran user and do not know C++ well enough. I need to make some additions into an existing C++ code. I need to create a 2d matrix (say A) of type double whose size (say m x n) is known only during the run. With Fortran this can be done as follows

real*8, allocatable :: A(:,:)
integer :: m, n    
read(*,*) m
read(*,*) n
allocate(a(m,n))
A(:,:) = 0.0d0

当在编译时不知道m和n时,如何在C ++中创建矩阵A(m,n)?我相信C ++中的运算符new可能有用,但不确定如何使用double来实现它.另外,当我在C ++中使用following

How do I create a matrix A(m,n), in C++, when m and n are not known at the time of compilation? I believe the operator new in C++ can be useful but not not sure how to implement it with doubles. Also, when I use following in C++

int * x;
x = new int [10];

并使用sizeof(x)/sizeof(x[0])检查x的大小,我没有10,为什么有任何评论?

and check the size of x using sizeof(x)/sizeof(x[0]), I do not have 10, any comments why?

推荐答案

要动态分配类似于2D数组的构造,请使用以下模板.

To allocate dynamically a construction similar to 2D array use the following template.

#include <iostream>

int main()
{
   int m, n;

   std::cout << "Enter the number of rows: ";
   std::cin >> m;

   std::cout << "Enter the number of columns: ";
   std::cin >> n;

   double **a = new double * [m];

   for ( int i = 0; i < m; i++ ) a[i] = new double[n]();

   //...

   for ( int i = 0; i < m; i++ ) delete []a[i];
   delete []a;
}

还可以使用类std::vector代替手动分配的指针.

Also you can use class std::vector instead of the manually allocated pointers.

#include <iostream>
#include <vector>

int main()
{
   int m, n;

   std::cout << "Enter the number of rows: ";
   std::cin >> m;

   std::cout << "Enter the number of columns: ";
   std::cin >> n;

   std::vector<std::vector<double>> v( m, std::vector<double>( n ) );

   //...

}

关于此代码段

int * x;
x = new int [10];

然后x具有类型int *,而x[0]具有类型int.因此,如果指针的大小等于4,并且int类型的对象的大小也等于4,则sizeof( x ) / sizeof( x[0] )将产生1.无论指针是指向单个对象还是指向第一个对象,指针都不会保留信息.对象是一些对象序列.

then x has type int * and x[0] has type int. So if the size of the pointer is equal to 4 and the size of an object of type int is equal also to 4 then sizeof( x ) / sizeof( x[0] ) will yields 1. Pointers do not keep the information whether they point to only a single object or the first object pf some sequence of objects.

这篇关于在C ++中声明和分配2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆