声明一个没有大小的多维数组 [英] Declare a multidimentional array without the size

查看:47
本文介绍了声明一个没有大小的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不知道大小的情况下声明一个数组数组或多维数组.

I want to declare an array of arrays or multidimensional array without knowing the size.

我想用简单的数组做一些类似于我在这种情况下所做的事情:

I want to do something similar to what I did in this cases with simple arrays:

int *array;
cin >> size;
array = new int[size];

也许我可以循环初始化这样的指针:

Maybe I can loop to initialize a pointer of pointers like this:

int **array;
cin >> rows >> col;
array = new *int[rows]
for (int i = 0; i < rows; ++i)
    array[i] = new int[col];

但如果有更好的解决方案,我宁愿不这样做.

But I would prefer to not do this if a better solution exists.

推荐答案

为什么不使用 std::vector?

Why not use std::vector?

std::vector<std::vector<int> > array;

如果不想使用指针数组,可以使用一个大数组,在获取大小后动态分配并作为行数组访问.

If you don't want to use an array of pointers, you could use one large array that you allocate dynamically after you get the size and access it as an array of rows.

int rows = 10;
int columns = 20;

int* array = new int[rows * columns];

for (int count = 0; count < rows; count++)
{
   int* row = &array[count * columns];

   for (int inner_count = 0; inner_count < columns; inner_count++)
   {
      int* element = &row[inner_count];

      //do something
   }
}

delete [] array;

这篇关于声明一个没有大小的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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