实现图的存储,输出存储结构示意图的代码;
时间: 2024-05-07 18:20:45 浏览: 10
以下是使用邻接表实现图的存储,并输出存储结构示意图的代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 边结构体
struct Edge {
int to; // 边的终点
int weight; // 边的权重
Edge(int t, int w) : to(t), weight(w) {}
};
// 邻接表存储图
class Graph {
private:
int V; // 图的顶点数
vector<vector<Edge>> adj; // 邻接表
public:
Graph(int v) : V(v), adj(v) {}
// 添加一条边
void addEdge(int from, int to, int weight = 1) {
adj[from].push_back(Edge(to, weight));
}
// 输出存储结构示意图
void print() {
for (int i = 0; i < V; i++) {
cout << i << " -> ";
for (auto& e : adj[i]) {
cout << e.to << "(" << e.weight << ") ";
}
cout << endl;
}
}
};
int main() {
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.print();
return 0;
}
```
输出结果如下所示,为存储结构示意图:
```
0 -> 1(1) 2(1)
1 -> 2(1)
2 -> 3(1)
3 -> 4(1)
4 ->
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)