C++ 中的二维步进数组

2 dimensional step array in c++

本文关键字:二维 步进 数组 C++      更新时间:2023-10-16

我是 c++ 的新手,我花了一晚上思考这个问题。我想创建一个二维数组,给出一维的长度。第二维的长度,从1增加。例如,对于二维数组 a[][],a[0][]

有 1 个元素,a[1][] 有 2 个元素,a[2][] 有 3 个元素,依此类推。

这听起来不像一个硬结构,但我找不到两个来创建它 - 我所能做的就是创建一个 x * x 数组,这意味着对我来说浪费了一半的空间。

有人知道吗? 提前谢谢。

std::vector解决方案:

vector< vector<int> > stairs;
for(int i = 0; i < n; i++) // n is size of your array
  stairs[i].resize(i+1);

您也可以使用纯指针执行此操作:

int * stairs[n];
for(int i = 0; i < n ; i++)
  stairs[i] = new int[i+1];

但是这次您将不得不担心在不再需要此结构时将其删除。

尝试考虑数组的动态分配。

动态阵列分配

制作多维数组的另一种方法是使用已知的概念 作为指向指针的指针。就像罗恩周四说的那样,大多数人认为 的 2D 数组,例如带有行和列的电子表格(这只是 很好),但是"引擎盖下",C++正在使用 PTR 到 PTRS。首先,你 从创建基指针开始。接下来,分配一个行数组 指针,并将第一个指针的地址分配给基指针。 接下来,分配内存以保存每行列数据并分配 行指针数组中的地址

但是,如果您是CPP的新手,我认为您不会处理大量数据,因此不必担心内存!

一种解决方案是定义一个类,该类保存大小为 x*(x+1)/2 的单维数据数组,并重载type & operator()(int r, int c)以执行正确类型的索引。

template<class datatype, int size>
class strange2dArray {
   datatype data[size*(size+1)/2];
   datatype & operator()(int r, int c) {
      // assert if the indexes are correct
      return data[r*(r+1)/2+c];
   }
};

顺便说一句,除非你这样做是为了学习C++,否则你可能应该使用某种数学库(或其他什么)来为你提供这样的基本数据结构。他们将更高效、更安全地实施它。

首先让我们看看 Python 的测试:

>>> a=[]
>>> a[0]=3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a={}
>>> a[0]=3

哎呀,看起来像数组,并不意味着它是数组。如果你想要"数组"的动态大小,你可以使用映射。是的,这是第一个解决方案:

#include <map>
#include <iostream> 
using namespace std;
typedef std::map<int, int> array_d2; //length of second dimensional is increased
array_d2   myArray[10] ; //length of first dimensional is given

int main()
{
myArray[0][1] = 3;
myArray[0][2] = 311;
//following are tests
cout << myArray[0][1] << endl;
cout << myArray[0][2] << endl;
return 0;
}

(输出是:)

$ ./test
3
311

我的第二个解决方案是使用 ,更像是一个数组,但具有调整大小功能,您应该覆盖操作 [] 以使其自动为用户使用。

#include <vector>
#include <iostream> 
using namespace std;
 //length of second dimensional is increased
class array_d2 {
    int m_size;
    vector<int> m_vector; 
  public:
    array_d2 (int size=10) {
        m_size = size;
        m_vector.resize(m_size);
    };
    int& operator[] ( int index ) {
        if (index >= m_size) {
        m_size = index + 1;
        m_vector.resize(m_size);
    }
    return m_vector[index];
    };
};
array_d2   myArray[10] ; //length of first dimensional is given

int main()
{
myArray[0][1] = 3;
myArray[0][20] = 311;
myArray[1][11] = 4;
myArray[1][12] = 411;

//following are tests
cout << myArray[0][1] << endl;
cout << myArray[0][20] << endl;
cout << myArray[1][11] << endl;
cout << myArray[1][12] << endl;
return 0;
}

(输出为)

$ ./test1
3
311
4
411