从c++到C: std::map的替代

Going down from C++ to C: alternative to std::map?

本文关键字:map std c++      更新时间:2023-10-16

我正在寻找std::map<long,>的简约替代方案,这将进入Windows内核驱动程序,所以它应该相当快。期望它能保存相对较小的键数(在工作集中约为200)和大量的插入。

寻找可以降低关键字搜索成本的解决方案

已经为你做好了。

参见RtlXxxGenericTable和RtlXxxGenericTableAvl调用。

  • RtlInitializeElementGenericTable
  • RtlDeleteElementGenericTable
  • RtlEnumerateGenericTable
  • RtlEnumerateGenericTableWithoutSplaying
  • RtlGetElementGenericTable
  • RtlInsertElementGenericTable
  • RtlLookupElementGenericTable
  • RtlNumberGenericTableElements

  • RtlInitializeElementGenericTableAvl

  • RtlDeleteElementGenericTableAvl
  • RtlEnumerateGenericTableAvl
  • RtlGetElementGenericTableAvl
  • RtlInitializeGenericTable
  • RtlInsertElementGenericTableAvl
  • RtlLookupElementGenericTableAvl
  • RtlNumberGenericTableElementsAvl

如果键的数量非常小,例如10或其他,也许您可以只使用线性搜索。如果您注意在内存中压缩键空间以最大化缓存命中,那么它可以非常快,并且在内存分配等方面的开销非常低。

在过去,对于少于几千个对象的映射,我发现创建一个std::vector按键值排序,然后使用二进制搜索来搜索,这比使用std::map要快得多。

您也可以在C中实现std::map语义。只有它不会是template

开头:

struct KeyValuePair
{
   KeyType key;
   ValueType value;
};
struct Map
{
   KeyValuePair *list; //it can be linkedlist as well
};
//these are the interfaces which operate on map
void Insert(Map * map, KeyType key, ValueType value);
void Update(Map * map, KeyType key, ValueType value);
int Find(Map * map, KeyType key, ValueType *outValue);
//Implement Get in terms of Find
ValueType Get(Map * map, KeyType key)
{
     ValueType value;
     Find(map, key, &value);
     return value;
}

STL map实现是红黑树我相信

http://en.wikipedia.org/wiki/Map_%28C%2B%2B%29

http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree

在C中需要两个配套数组:一个用于键,另一个用于值。如果您可以将两者封装起来,这样用户就可以坚持使用映射语义。

如果你需要用C语言实现一个简单的字典,那么有一天用C语言实现一个字典会更有趣……但我们并不总是有时间去做。

所以你可以试着看看inparser模块1,它是一个小字典,可以在内核和/或嵌入式世界中使用

相关文章: