C ++中多维数组的动态内存分配 [英] Dynamic Memory Allocation in C ++ for Multi Dimentional Array
问题描述
大家好
我正在寻找二维数组中的动态内存分配.在C ++中
我真正需要的是我需要"N"个数组数,其中我仅在运行时会得到"N"的值.
每个数组的大小都为"Z",其中Z对于不同的数组将是不同的.
我想到了将二维数组用于同一数组,以便将所有射线组合成一个数组,但是问题是每个数组中的元素数都不相同.
例子是:
假设在运行时用户给出我需要输入4种类型的数据,所以在这里,N = 4
第一组有10个物品,所以这里z = 10
第二个有23个项目,所以这里z = 23
3rd有12个商品,所以这里z = 12
第四有90件.所以这里z = 90
这就是我需要的
任何指针!
如果我可以在C ++中使用相同的代码,那将是一个很大的帮助.
在此先感谢
Hi all
I am looking for Dynamic memory allocation in 2-D array. in C++
What exactly i Require is that I need ''N '' Number of Arrays, where in I would get value of ''N'' at runtime only.
Each Array would be of size say '' Z '', wherein Z would be differnt for different array.
I thought of having 2-D array for the same, so that I can have all arays combined in one, But then the problem is that number of element is different in each array.
example is :
Suppose at Runtime user gives that i need to enter 4 types of data, so here, N=4
The
1st set has 10 items, so here z=10
2nd has 23 items, so here z=23
3rd has 12 items, so here z=12
4th has 90 items. so here z=90
This is what i require
Any pointer !!!
It would be a great help if i can have a code in C++ for the same.
Thanks in Advance
推荐答案
您可以为此使用向量矢量.
假设您要存储的内容是int
,那么您将创建一个矢量--
You can use a vector of vectors for this.
Suppose the contents you want to store areint
s then you would create such a vector as -
std::vector<std::vector<int>> vvInt;
要分配第一组10个值,您可以执行以下操作-
To assign the first set of 10 values you could do this -
std::vector<int> vInt;
for (int i = 0; i < 10; ++i)
{
vInt.push_back(i);
}
现在,将第一个集合添加到向量的向量中.
Now add this first set to the vector of vectors.
vvInt.push_back(vInt);
同样-
Similarly -
vInt.clear();
for (int i = 0; i < 23; ++i)
{
vInt.push_back(i);
}
vvInt.push_back(vInt);
感谢您的解决方案.
甚至对我也有用
cout<< 输入要测试的套数";
cin>> size_x;
a = new int * [size_x];
/* a = new(size_x * sizeof(int *)); */
对于(i = 0; i< size_x; i ++)
{
cout<< 输入组的编号elemnets";
cin>> size_y;
a [i] = new int [size_y +1];
/* a [i] = new(size_y * sizeof(int)); */
for(j = 1; j< = size_y; j ++)
{
a [i] [0] = size_y;
cout<< 输入元素";
cin>> a [i] [j];
}
}
Thanks For the solution.
Even this worked for me
cout << " Enter the number of sets you want to test ";
cin >> size_x;
a= new int *[size_x];
/* a = new (size_x * sizeof(int *)); */
for (i = 0; i < size_x; i++)
{
cout << " Enter the number elemnets for group ";
cin >> size_y;
a[i]= new int [size_y +1];
/* a[i] = new (size_y * sizeof(int)); */
for (j = 1; j <= size_y; j++)
{
a[i][0]=size_y;
cout << " Enter the elements " ;
cin >> a[i][j] ;
}
}
在这里,您必须注意分配和释放内存.
如果未正确完成此操作,则将发生内存泄漏.
vector
将在内部为您分配内存,以确保没有内存泄漏.
Here you have to take care of allocating and deallocating memory.
If this is not done properly you will have memory leaks.
Avector
will internally take care of memory allocation for you guaranteeing no memory leaks.
这篇关于C ++中多维数组的动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!