我可以在每行中有一个不同数量的列数组吗?

Can I have an array with different number of columns in each row?

本文关键字:数组 有一个 我可以      更新时间:2023-10-16

我想使用一个数组来存储图形的邻接列表。其中每个节点具有不同数量的节点连接到它。因此,我只想拥有以下类型的数组:

Row 0: 1 5 3
Row 1: 0 2 3
Row 2: 1
Row 3: 0 1 5 4
Row 4: 3 5
Row 5: 0 1 3 4 

您可以使用 int 向量的向量,其中每行您可以存储不同数量的元素(节点(。

以下是示例代码。

#include <iostream>
#include <vector>
int main()
{
    using Row = std::vector<int>;
    std::vector<Row> rowVec;
    rowVec.reserve(6); // reserve memory if you know the size beforehand.
    // emplace each row of elements to the vector of vectors
    rowVec.emplace_back(Row{ 1, 5, 3 }); 
    rowVec.emplace_back(Row{ 0, 2, 3 });
    rowVec.emplace_back(Row{ 1 });
    rowVec.emplace_back(Row{ 0, 1, 5, 4 });
    rowVec.emplace_back(Row{ 3 ,5 });
    rowVec.emplace_back(Row{ 0, 1, 3, 4 });
    // to iterate throw the vector of vectors
    for (const Row& row : rowVec)
    {
        for (const int element : row)
            std::cout << element << " ";
        std::cout << 'n';
    }
    return 0;
}

输出

1 5 3 
0 2 3 
1 
0 1 5 4 
3 5 
0 1 3 4 

使用new关键字可以部分实现,但您的想法并非完全可以实现。对于3D数组,所有元素必须具有相同大小的第一维。此外,其中的每个2D数组必须具有相同的行维度。一个3D数组不过是一系列数组或更像矩阵数组。让我们的3D阵列成为一个看起来像:

A = [[[y1_x1,y1_x2],[y2_x1,y2_x2]],[[y3_x1,y3_x2,],[y4_x1,y4_x2]]]

这是两个元素A[0]A[1]在每个内部,还有其他两个元素A[0][0], A[0][1]A[1][0], A[1][1]这四个元素中有其他两个要素:

A[0][0][0]// which is y1_x1
A[0][0][1]// which is y1_x2
A[1][1][0]// which is y2_x1
A[1][1][1]// which is y2_x2
A[1][0][0]// which is y3_x1
A[1][0][1]// which is y3_x2
A[1][1][0]// which is y4_x1
A[1][1][1]// which is y4_x2

现在想象,[0]和a [1]的一个元素之一可能是矩阵,另一个仅是一个值,例如:

A = [[[y1_x1,y1_x2],[y2_x1,y2_x1]],y3]

有4种参考[0]的方法,只有1种参考[1]的方法在第二个维度中也可能是这种情况:

A = [[[y1_x1,y1_x2],],y2], y3]

有两种方法可以参考[0] [0],但对于[0] [1]。

您可以创建一系列指针,每个指针都引用数组。

int ***z;
z = new int**[z-size];
z[0] = new int*[y-size];
z[1] = new int*[y-size];
...
z[0][0] = new int[x-size];
z[0][1] = new int[x-size]

当然,如果尺寸相同

,可以使用for循环来简化此过程