您想要的(不借助 Boost)是我所说的“有序哈希”,它本质上是哈希和带有字符串或整数键(或两者同时)的链表的混搭。有序散列在迭代期间保持元素的顺序,具有散列的绝对性能。
我一直在整理一个相对较新的 C++ 片段库,它填补了我认为 C++ 库开发人员在 C++ 语言中的漏洞。到这里:
https://github.com/cubiclesoft/cross-platform-cpp
抓住:
templates/detachable_ordered_hash.cpp
templates/detachable_ordered_hash.h
templates/detachable_ordered_hash_util.h
如果将用户控制的数据放入哈希中,您可能还需要:
security/security_csprng.cpp
security/security_csprng.h
调用它:
#include "templates/detachable_ordered_hash.h"
...
// The 47 is the nearest prime to a power of two
// that is close to your data size.
//
// If your brain hurts, just use the lookup table
// in 'detachable_ordered_hash.cpp'.
//
// If you don't care about some minimal memory thrashing,
// just use a value of 3. It'll auto-resize itself.
int y;
CubicleSoft::OrderedHash<int> TempHash(47);
// If you need a secure hash (many hashes are vulnerable
// to DoS attacks), pass in two randomly selected 64-bit
// integer keys. Construct with CSPRNG.
// CubicleSoft::OrderedHash<int> TempHash(47, Key1, Key2);
CubicleSoft::OrderedHashNode<int> *Node;
...
// Push() for string keys takes a pointer to the string,
// its length, and the value to store. The new node is
// pushed onto the end of the linked list and wherever it
// goes in the hash.
y = 80;
TempHash.Push("key1", 5, y++);
TempHash.Push("key22", 6, y++);
TempHash.Push("key3", 5, y++);
// Adding an integer key into the same hash just for kicks.
TempHash.Push(12345, y++);
...
// Finding a node and modifying its value.
Node = TempHash.Find("key1", 5);
Node->Value = y++;
...
Node = TempHash.FirstList();
while (Node != NULL)
{
if (Node->GetStrKey()) printf("%s => %d\n", Node->GetStrKey(), Node->Value);
else printf("%d => %d\n", (int)Node->GetIntKey(), Node->Value);
Node = Node->NextList();
}
在我的研究阶段,我遇到了这个 SO 线程,看看是否已经存在像 OrderedHash 这样的东西,而不需要我进入一个庞大的库。我很失望。所以我自己写了。现在我已经分享了它。