需要两个为Glist对象的减法在C
问题描述:
g1和g2是存在以下字符(未一个char **)一个为Glist对象
g1 = {"a", "b", "c"};
g2 = {"b", "d", "e"};
我需要用c的码返回列表减法的glist库;
g3 = subtract (g1, g2);
should return
{"a", "c");
g4 = subtract (g2, g1);
should return
{"d", "e");
答
void glist_deep_copy_g_func(gpointer data, gpointer user_data) {
GList** result = user_data;
if (data) {
*result = g_list_append(*result, strdup(data));
}
user_data = result;
}
GList* glist_deep_copy(GList* source) {
GList* result = NULL;
g_list_foreach(source, &glist_deep_copy_g_func, &result);
return result;
}
gint glib_compare_char_ptr(gconstpointer a, gconstpointer b) {
return strcmp(a, b);
}
GList* glist_subtract(GList* from, GList* by) {
GList* result = NULL;
if (from && by) {
result = glist_deep_copy(from);
for (GList *node_from = g_list_first(from); node_from; node_from =
g_list_next(node_from)) {
for (GList *node_by = g_list_first(by); node_by; node_by =
g_list_next(node_by)) {
if (!strcmp(node_from->data, node_by->data)) {
GList* node = g_list_find_custom(result, node_from->data,
&glib_compare_char_ptr);
char* data = node->data;
result = g_list_remove(result, node->data);
free(data);
}
}
}
} else if (from) {
return glist_deep_copy(from);
}
return result;
}
答
您可以查看的std::set_difference
实施和适应它glist
。
GLib本身没有设置差异的实现。
+0
但这是为c,而不是C++。 –
+0
我说'适应',而不是'复制粘贴'。这个想法可以在代码中看到,实现可以用纯C和glist结构重写。 OP只需要牢记C++算法中的迭代器与指向C中列表项的指针是一样的。 – Jurlie
这是功课吗? – Jurlie
不,它不是家庭作品 –
[Glib - Glist示例中的说明](https://developer.gnome.org/glib/stable/glib-Doubly-Linked-Lists.html)可能对您有用。 –