从 (search.h) 哈希搜索 table 中获取所有键

Get all keys from (search.h) hash search table

我正在使用 search.h 库通过 hcreate 函数定义散列 table。

如何遍历 table 中的所有键? hsearch 总是需要一个条目来搜索(或存储)。

This 是管理散列 table(hcreatehsearchhdestroy)的所有三个函数的文档,但没有提及如何遍历结构以获取所有存储的键。

在 table 中存储条目时,我 malloc 键值,因此希望有一种简单的方法来释放那些 malloc 的值。

我能否避免将它们存储在单独的结构(如数组)中?

我不希望 hdestroy 自动为我执行此操作,因为它无法知道 key 是否指向动态分配或静态内存(或者实际上我是否没有'尚未释放该内存)。

切换到不同的哈希搜索 table 库不是一个选项。我必须解决这个问题。我在 CentOS 上并使用 GCC 4.1.2。

没有迭代散列条目的标准功能table。此问题已解决 here(在 hdestroy 部分):

It is important to remember that the elements contained in the hashing table at the time hdestroy is called are not freed by this function. It is the responsibility of the program code to free those strings (if necessary at all). Freeing all the element memory is not possible without extra, separately kept information since there is no function to iterate through all available elements in the hashing table. If it is really necessary to free a table and all elements the programmer has to keep a list of all table elements and before calling hdestroy s/he has to free all element’s data using this list. This is a very unpleasant mechanism and it also shows that this kind of hashing tables is mainly meant for tables which are created once and used until the end of the program run.

如果不查看库的实际来源,我会说在哈希 table 创建后无法遍历它。您将需要在单独的结构中记住您的 malloc 内存的指针。

坦率地说,我认为我不会用十英尺长的杆子去碰那个图书馆。 API 有很多问题

  • 糟糕的文档
  • 库只能支持单个散列 table(请注意 hcreate 不 return 句柄然后传递给 hsearchhdestroy)
  • 无法步行 table 或取回钥匙严重限制了它的使用。

相反,根据您的平台(您没有说您是在 Windows 还是基于 Unix 的 OS),我会仔细研究 glib 支持丰富的数据结构 (documentation home)

哈希 table 的文档是 here。这是库的 v2.42 - 他们没有 "latest version".

的通用 link

glib 是 GNOME 的核心(Ubuntu UI),但您不需要使用任何 gmainloop 或事件泵相关的功能。