免责声明:这篇文章的作者是 C++ 初学者。
在我的 Erlang 代码中,我有一个表示有向图的数据结构:
-record(vertex_entry, {vertex_name, outgoing_edges}).
-record(outgoing_edge, {edge_weight, neighbour_name}).
Edge1 = #outgoing_edge{edge_weight = 12.5, neighbour_name = 2},
Edge2 = #outgoing_edge{edge_weight = 11.2, neighbour_name = 3},
Edges = [Edge1,Edge2],
Vertex1 = #vertex_entry{vertex_name = 1, outgoing_edges = Edges},
Vertex4 = #vertex_entry{vertex_name = 4, outgoing_edges = Edges},
Graph = [Vertex1,Vertex4].
我想通过 Erlang 的端口功能将此图传递给 C++。
在 C++ 方面,我想将此 Erlang 图转换为以下结构的图(它是 CUDA 优化的邻接列表 structure ):
typedef struct
{
// (V) This contains a pointer to the edge list for each vertex
int *vertexArray;
// Vertex count
int vertexCount;
// (E) This contains pointers to the vertices that each edge
// is attached to
int *edgeArray;
// Edge count
int edgeCount;
// (W) Weight array
float *weightArray;
} GraphData;
或许,来自同一来源(本书第 16 章)的 C++ 图生成代码将有助于解决这个问题:
void generateRandomGraph(GraphData *graph, int numVertices, int neighborsPerVertex)
{
graph->vertexCount = numVertices;
graph->vertexArray = (int*) malloc(graph->vertexCount * sizeof(int));
graph->edgeCount = numVertices * neighborsPerVertex;
graph->edgeArray = (int*)malloc(graph->edgeCount * sizeof(int));
graph->weightArray = (float*)malloc(graph->edgeCount * sizeof(float));
for(int i = 0; i < graph->vertexCount; i++)
{
graph->vertexArray[i] = i * neighborsPerVertex;
}
for(int i = 0; i < graph->edgeCount; i++)
{
graph->edgeArray[i] = (rand() % graph->vertexCount);
graph->weightArray[i] = (float)(rand() % 1000) / 1000.0f;
}
}
我假设 Erlang 的端口功能将帮助我以二进制格式将数据从 Erlang 传递到 C++。
所以,问题是: 如何在 C++ 代码中将某个 Erlang 数据结构(表示图形)恢复并转换为上述用户指定的 C++ 图形数据结构?
最佳答案
除非性能在这里很关键,否则请考虑以易于解析的格式序列化为文本。如果您可以读取输出、在测试读取端时将其保存到文件等,它将为您节省大量调试工作。
即使您决定切换到二进制编码,先写出文本编码也可能有助于决定布局。我对你的其他问题的回答应该给你一个关于在 C++ 端读取二进制而不是文本输入的基础知识的指针。
此外,如果您是 C++ 的新手,如果可能的话,您不妨从良好的惯用风格开始:考虑更换您的 int*
数组和手动分配 std::vector<int>
等
关于c++ - 如何将 Erlang 数据结构转换为 C++ 邻接表(图形)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807635/