我可以在每行中有一个不同数量的列数组吗?
Can I have an array with different number of columns in each row?
我想使用一个数组来存储图形的邻接列表。其中每个节点具有不同数量的节点连接到它。因此,我只想拥有以下类型的数组:
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
循环来简化此过程
相关文章:
- 在c++中为double类型的数组创建一个unique_ptr
- 从数组构造一个跨度<shared_ptr<T>><shared_ptr<void>>
- C++,数组有多少个地址?
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何将 v8::FunctionCallbackInfo<v8::Value> 数组从一个隔离复制到另一个隔离?
- 将任意对象附加到数组有什么问题
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- 为什么我的数组输出一个不在其中的元素
- 堆指针不会被分配给数组有什么原因吗
- 数组 - 最后一个索引
- C/C++ 中的常量数组和静态常量数组有什么区别
- 将数组作为一个参数从一个函数传递到C 中的另一个函数
- 从字符串数组创建一个字符数组
- 如何在C 中的小写中将文本从数组的一个维度传递到另一个维度
- 在对结构数组的一个成员进行排序后,移动其成员的其余部分
- 为什么数组在一个文件中打印,但在发送到另一个文件时却缺少数字
- C++,为什么多维数组的一个元素的增加似乎增加了另一个元素
- 将数组的一个元素与整个数组元素进行比较
- 如何将数组从一个函数传递到另一个函数
- 如何使用object.get()将文本读取到一个参数比文本大的2D数组中(2D数组有更多的行和列)