c++代码实现图的基本操作
时间: 2023-12-05 21:35:04 浏览: 36
以下是使用C++实现图的基本操作的示例代码:
```cpp
#include <iostream>
#include <list>
using namespace std;
class Graph {
int numVertices; // 图中顶点的数量
list<int> *adjLists; // 存储邻接表的数组
public:
Graph(int vertices) {
numVertices = vertices;
adjLists = new list<int>[vertices];
}
void addEdge(int src, int dest) {
// 将目标顶点添加到源顶点的邻接表中
adjLists[src].push_back(dest);
// 由于是无向图,所以也需要将源顶点添加到目标顶点的邻接表中
adjLists[dest].push_back(src);
}
void removeEdge(int src, int dest) {
// 从源顶点的邻接表中移除目标顶点
adjLists[src].remove(dest);
// 从目标顶点的邻接表中移除源顶点
adjLists[dest].remove(src);
}
void printGraph() {
for (int i = 0; i < numVertices; i++) {
cout << "顶点 " << i << " 的邻接表: ";
for (const auto& vertex : adjLists[i]) {
cout << vertex << " ";
}
cout << endl;
}
}
};
int main() {
Graph g(5); // 创建一个包含5个顶点的图
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.printGraph();
g.removeEdge(1, 4);
cout << "移除边 (1, 4) 后的图:" << endl;
g.printGraph();
return 0;
}
```
此代码使用邻接表表示图,并实现了添加边、删除边和打印图的功能。你可以根据需要自行修改和扩展。