相关概念
- 如下图所示:适合存储稀疏图,适合查找一个顶点出去的边,但不适合确定两个顶点是否连接及权值
实现基础框架
Edge结构体
template <class W>
struct Edge{
int _dsti;
W _w;
Edge<W>* _next;
Edge(int dsti, W w)
:_dsti(dsti)
, _w(w)
, _next(nullptr){
}
};
Graph_table
template <class V, class W, bool Direction=false>
struct graph_tables{
public:
typedef Edge<W> Edge;
private:
vector<V> _vertex;
unordered_map<V, int> _indexMap;
vector<Edge*> _tables;
};
构造函数
- 初始化_vertex顶点表,并记录顶点与下标的映射关系;初始化_tables邻接表
graph_tables(const V* array, size_t n){
_vertex.reserve(n);
for (size_t i = 0; i < n; i++){
_vertex.push_back(array[i]);
_indexMap[array[i]] = i;
}
_tables.resize(n, nullptr);
}
实现基础操作
获取某一顶点的下标
添加边
- 根据目的顶点及权值构造边-----头插到对应的链表后面
void addEdge(const V& src, const V& dst, const W& w){
int srci = getVertexIndex(src);
int dsti = getVertexIndex(dst);
Edge* edge = new Edge(dsti, w);
edge->_next = _tables[srci];
_tables[srci] = edge;
if (Direction == false){
Edge* edge = new Edge(srci, w);
edge->_next = _tables[dsti];
_tables[dsti] = edge;
}
}
打印邻接表
void print(){
for (size_t i = 0; i < _vertex.size(); i++){
cout << "[" << _vertex[i] << "] -> " << i << endl;
}
for (size_t i = 0; i < _tables.size(); i++){
Edge* cur = _tables[i];
cout << "[" << _vertex[i] << "] -> ";
while (cur != nullptr){
cout << cur->_dsti << ": " << cur->_w << "-> ";
cur = cur->_next;
}
cout << "nullptr" << endl;
}
}