我正在尝试编写一个具有以下要求的简单无向图节点:
-可以存储任何类型的数据
-存储指向所有邻居的指针
-在图节点struct中具有可以添加/删除邻居的功能。这样我可以简单地调用:node.add_neighbor(other_node);
我目前有以下内容:
struct GraphNode{
int number_of_connected_nodes;
struct TreeNode** neighbors; //dynamically resize as neighbors are added/removed
void *data;
void(*add_neighbor)(struct GraphNode * self,other)
//how do I ensure that "this" object is always passed to self in the function pointer?
}
static void connect_node(struct GraphNode * self,other){
self->number_of_connected_nodes=self->number_of_connected_nodes+1;
self->connected_nodes=realloc(self->connected_nodes,self->number_of_connected_nodes * sizeof(struct GraphNode*));
self->connected_nodes[(self->number_of_connected_nodes -1)] =other;
}
struct GraphNode* create_graph_node() {
struct GraphNode *graph_node = malloc(1 * sizeof(struct GraphNode));
graph_node->number_of_connected_nodes = 0;
graph_node->neighbors = NULL;
graph_node->add_neighbor=connect_node;
}
我遇到的主要问题是,如果我使用函数指针,我不知道如何将邻居添加到对象本身作为结构的一部分。
我也非常感谢其他任何想法或意见,以帮助我更好地做到这一点。
答案 0 :(得分:0)
最常见的约定是:
#define AddNode(from, to) (from)->add_neighbour((from), (to))
如果您担心图书馆的某些客人惹上您,请不要担心。他们总能找到一种方法来颠覆您的后卫,这是什么语言。
如果您希望使用简洁的语法,Go是一个不错的选择。它保持了C令人愉快的位置,而不会陷入其他C衍生物所具有的麻烦。