gpt4 book ai didi

c# - C# 字典是如何实现的? (C++)

转载 作者:行者123 更新时间:2023-11-30 01:25:14 27 4
gpt4 key购买 nike

<分区>

您好,我正在使用 C++ 创建一个类似于 C# 的字典对象。对于程序运行时在内存中移动的所有内容,我都使用类似的垃圾收集 ref 对象系统。我已经开始实现字典 aa 一个非常标准的哈希表,这很好,我有这种类型的布局:

header + hash table -> storage -> element 0 -> object x
element 1 -> object y
element ... -> object ...

'+': In same allocation
'->': Indirect pointer ie different allocation

因此“标题”仅包含表格大小。 '哈希表'是存储区域中的整数偏移量数组。

存储实现为 C# 列表,即指向自调整数组的间接指针(ref 对象),即类似于 C++ vector 。

存储中的每个元素 (Dictionary::Element) 都包含一个 id、一个指向实际对象的间接指针(ref 对象)和一个指向下一个元素的整数偏移量。

// C++ like pseudo code:
template< typename _Type_, typename _HashType_ = int >
class Dictionary
{
private:

class Element
{
_HashType_ m_id;
_Type_ m_object; // Ref object ie indirect pointer to actual object
int m_next; // Next element
}

int m_tablesize; // Power of 2
int* m_table; // Pointer here but in reality just a continuous block
// of memory after m_tablesize;
List<Element> m_storage; // Like a C++ vector
}

所以我的问题是 C# 的字典一次只允许一个对象用于任何一个散列。

是否有比上述实现更简单的方法?

例如 Dictonary::Add(_HashType_ id, _Type_ object) 在上面的实现中将按位与散列与表大小进行运算以获得散列表中的索引,然后分配一个元素id 和 object 传入,然后它将该元素添加(推回)到元素列表(m_storage)并修复元素链表:

template < typename _Type_, typename _HashType_ >
inline bool Dictionary< _Type_, _HashType_ >::Add( _HashType_ id, _Type_ element )
{
Element element = Element::New( id, object );
m_storage->Add( element );

// PushBack here fixes up the offset of the element in the storage array stored in
// the hash table (zero elements for this id) or the next pointer in the element
// (one or more elements exist for this id)
return PushBack( element );
}

更明确一点:有没有办法只拥有对象的 header 和哈希表,即:

header + hash table -> object x
object y
...

我问这个是因为当上面更复杂的实现实际上没有这样的限制时,C# 对每个散列施加了一个项目限制,除了 Remove 需要同时传递 id 和对象,并且可能你可能想要 PushFront 和 PushBack 而不是添加。

提前致谢,请不要问我为什么要做这件看似疯狂的事情,只是逗我开心! :)

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com