有向邻接表图中不同大小边的存储

Storage of different-sized edges in directed adjacency-list graph

本文关键字:存储      更新时间:2023-10-16

设置如下:

class Vertex;
class Edge {
    Vertex *to;
};
class Teleport : public Edge {
    int teleportCost;
};
class Walk : public Edge {
    double distance;
};
class Vertex {
    vector<Edge> adjacencies; // can only store Edge and not Walk, Teleport etc!
};

问题当然是Vertex可以有许多不同类型的邻接,每个邻接都有不同的字节大小。那么,存储这些边的最好方法是什么呢?我的图永远不会移除顶点或边;一旦它被完全构建,它就会保存在内存中,直到它被一次全部销毁。也许这将允许在一个大内存池或足够大的vector中"全局"存储字节,然后每个Vertex都有一个vector<void*>vector<Edge*>或指向内存缓冲区的其他东西。然而,我不确定如何做到这一点。有没有人可以提供一些指导,告诉我在我的场景中最好使用什么作为存储?

所有的Edge将被多态使用,所以我从不需要转换到Teleport等。

当一个类型被指定为子类型时,这种类型的vector或对象数组几乎总是错误的。您需要存储一个向量或指针数组。

代替:

vector<Edge> adjacencies;
使用

vector<std::share_ptr<Edge>> adjacencies;