有人用 ANSI C 写过字典(哈希图)吗?
我只是想知道是否有人可以给我一些指示(没有双关语)如何做到这一点?
我想留出 4GB 内存,以便将数字映射到内存,这样我就不用遍历链表来检查它们是否存在。
因此,我希望能够在 O( 中查找键“2343”,而不是使用 (1,2,3,4,8,34,543,2343) 并遍历 8 个元素来验证“2343”是否在列表中1)时间?
提前致谢
I just wondered if someone could give me some pointers (no pun intended) how to do this?
I want to set aside 4GB of ram in order to map numbers to memory which saves me traversing a linked list checking if they are there.
So instead of having (1,2,3,4,8,34,543,2343) and traversing 8 elements to verify that '2343' is in the list, i want to be able to look up the key '2343' in O(1) time?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议在您的项目中嵌入 Lua 。易于嵌入且完全符合 ANSI C,具有一种非常灵活的垃圾收集数据结构(Lua 表/又名哈希图)。你总是可以去掉不需要的部分,但即使你不这样做,Lua 也是很小的。
Lua 有一个基于堆栈的 API,这并不难理解:
您也可以迭代这些值,可能不需要链表(但迭代的顺序是不确定的)。完整手册此处。
I would advise embedding Lua in your project. Easy to embed and completely ANSI C with one very flexible garbage collected data structure (a Lua table/aka hashmap). You can always strip out the bits that you don't need, but even if you don't Lua is tiny.
Lua has a stack based API which isn't too hard to follow:
And you can iterate over the values as well, possibly doing away with the need of your linked list (but the order of the iteration is non-determinate). Full manual here.
如果您只需要检查列表中是否存在该数字,则可以尝试制作位图。
如果数字稀疏地分布在一个大范围内,例如 0-40 亿范围内的 100,000 个值,那么哈希表会更快。对于 Hashtable 的 C 实现看看 GLib 的 Hashtable。
位图仅使用 512 MB 的 RAM 即可保存数字 0-4,294,967,295。
If you only need to check if the number exists in the list, the you can try to make a Bitmap.
If the numbers are going to be sparsely spread out over a large range like 100,000 values in the range 0-4billion then a Hashtable would be faster. For a C implementation of a Hashtable take a look at GLib's Hashtable.
A Bitmap could hold numbers 0-4,294,967,295 using only 512Mbytes of ram.
如果数字是 32 位,则甚至不需要散列,只需使用数组即可。
If the numbers are 32 bits you don't even need hashing, just use an array.
当没有具有相同哈希值的键时,哈希表实际上只有 O(1)。
有关 C 中哈希表的简单简短版本,请参见此处:
http://pokristensson.com/strmap.html
A hashtable is actually only O(1) when there are no keys that have the same hash.
For an easy short version of a hashtable in C look here:
http://pokristensson.com/strmap.html