c++用vector存储无向图代码
时间: 2023-07-27 08:25:04 浏览: 39
以下是使用 vector 存储无向图的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m; // n 为节点数,m 为边数
cin >> n >> m;
vector<vector<int>> graph(n + 1); // 使用 vector 存储无向图
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
return 0;
}
```
上述代码中,`graph` 是一个二维 vector,其中 `graph[i]` 表示节点 i 的邻接点集合。在输入边的信息时,将边的两个端点 u 和 v 加入到彼此的邻接点集合中即可。
相关问题
C++代码关于创建无向图的邻接表存储结构
以下是使用邻接表存储结构创建无向图的 C++ 代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 邻接表存储结构中的边结构体
struct Edge {
int to; // 边的终点
int weight; // 边的权重
Edge(int t, int w) : to(t), weight(w) {}
};
// 邻接表存储结构中的顶点结构体
struct Vertex {
int id; // 顶点编号
vector<Edge> adj; // 存储与该顶点相邻的所有边
Vertex(int i) : id(i) {}
};
// 创建无向图的邻接表存储结构
vector<Vertex> createGraph(int n, vector<vector<int>>& edges) {
vector<Vertex> graph(n);
for (auto& e : edges) {
int u = e[0], v = e[1], w = e[2];
graph[u].adj.emplace_back(v, w);
graph[v].adj.emplace_back(u, w);
}
return graph;
}
int main() {
int n = 5; // 图中顶点个数
vector<vector<int>> edges = {{0, 1, 2}, {0, 4, 1}, {1, 2, 3}, {1, 3, 4}, {2, 3, 5}}; // 图的边集合
auto graph = createGraph(n, edges);
cout << "图的邻接表存储如下:" << endl;
for (int i = 0; i < n; ++i) {
cout << "顶点" << i << "的邻接表为:";
for (auto& e : graph[i].adj) {
cout << "(" << e.to << "," << e.weight << ") ";
}
cout << endl;
}
return 0;
}
```
上述代码中,我们先定义了邻接表存储结构中的边结构体 `Edge` 和顶点结构体 `Vertex`,然后通过 `createGraph` 函数创建无向图的邻接表存储结构,最后输出每个顶点的邻接表。其中,函数 `createGraph` 的输入参数包括图中顶点个数 `n` 和边集合 `edges`,输出参数为无向图的邻接表存储结构 `vector<Vertex>`。在函数中,我们遍历边集合 `edges`,对于每条边 `(u, v, w)`,分别将 `(v, w)` 和 `(u, w)` 添加到顶点 `u` 和 `v` 的邻接表中,以此创建无向图的邻接表存储结构。
以邻接表存储创建无向图的代码
以下是使用邻接表存储创建无向图的代码示例:
```c++
#include<iostream>
#include<vector>
using namespace std;
// 存储每个节点及其相邻节点的链表
struct Node{
int val; // 节点值
vector<int> adj; // 与该节点相邻的节点
};
int main(){
int n, m; // n个节点,m条边
cin >> n >> m;
vector<Node> graph(n+1); // 存储图的数组,下标从1开始
// 读入边并建立邻接表
for(int i=0; i<m; i++){
int u, v; // 边的两个节点
cin >> u >> v;
// 加入相邻节点
graph[u].adj.push_back(v);
graph[v].adj.push_back(u);
}
return 0;
}
```
以上代码中,我们利用结构体 `Node` 存储每个节点及其相邻节点的链表。在读入每条边时,我们将它的两个节点加入对方的相邻节点中,这样就建立了无向图的邻接表。