Him*_*ani 2 c++ algorithm graph multidimensional-array data-structures
我想使用一个数组来存储图的邻接表。其中每个节点具有连接到其的不同数量的节点。所以我只想拥有以下类型的数组:
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
Run Code Online (Sandbox Code Playgroud)
您可以使用向量的向量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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 5 3
0 2 3
1
0 1 5 4
3 5
0 1 3 4
Run Code Online (Sandbox Code Playgroud)