您想要的(无助于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之类的东西,而无需我放入庞大的库中。我很失望。所以我写了我自己的。现在,我已经分享了。