gpt4 book ai didi

c++ - C++ Graph类指针困惑

转载 作者:行者123 更新时间:2023-12-02 10:12:57 26 4
gpt4 key购买 nike

我正在尝试建立一个图类,其中图由邻接表表示。图本身是指针的 vector ,其中每个指针都指向节点的链接列表。无论出于何种原因,当我使用打印图形功能时,程序都不会输出任何内容。谁能告诉我我做错了什么,也许我对指针的误解在哪里?提前致谢!

#include <array>
#include <vector>
#include <tuple>
#include <unordered_map>

class Node
{
public:

int vertex;
int value;
Node* next;

Node(int ver)
{
vertex = ver;
};
};

class Graph
{
public:

int n_nodes;
std::unordered_map<int,Node*> graph;

Graph(int n)
{
n_nodes = n;
for(int i=0;i<n;i++)
{
graph.insert({i,nullptr});
};
};

void add_edge(int src,int des,int val)
{
Node node_des = Node(des);
node_des.value = val;
node_des.next = graph[src];
graph[src] = &node_des;

Node node_src = Node(src);
node_src.value = val;
node_src.next = graph[des];
graph[des] = &node_src;
};

void print_graph()
{
for(int i =0; i<n_nodes;i++)
{
std::string str = "Head "+std::to_string(i);
Node node = *graph[i];
while (&node != nullptr)
{
str=str+" -> "+std::to_string(node.vertex);
node = *(node.next);
};

std::cout<<str<<std::endl;
};
};
};

int main()
{
Graph g = Graph(6);
g.add_edge(0,1,3);
g.add_edge(2,1,4);
g.add_edge(0,4,1);
g.add_edge(4,5,6);
g.add_edge(5,3,2);
g.add_edge(4,3,3);
g.add_edge(3,2,5);
g.add_edge(4,1,1);
g.add_edge(3,1,2);

g.print_graph();
return 0;
}```

最佳答案

如果可能的话,您可以只使用vector的vector而不是链表,而不使用指针。由于内存缓存在 vector 操作中的某些插入可能比链表更快,因此结构如下:

struct Node2 {
int vertex;
int value;
};

struct Edge2 {
int src, des, value;
};

struct Graph2 {
int n_nodes;
std::vector<std::vector<Node2>> graph;

void add_edge(Edge2 edge) {
graph[edge.src].emplace_back(edge.des, edge.value);
graph[edge.des].emplace_back(edge.src, edge.value);
}

void add_edge(std::initializer_list<Edge2> edges)
{
std::for_each(edges.begin(), edges.end(), [this](auto &e) { add_edge(e); });
};
}
最终比链接列表更容易,更快捷;
https://quick-bench.com/q/cmX2-2IYA873TR4qn5aV4ijjUQo

关于c++ - C++ Graph类指针困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62853175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com