gpt4 book ai didi

c# - 设置 SortedDictionary 的第 i 个值

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:30 24 4
gpt4 key购买 nike

我需要在我的 sortedDictionary 中设置一个元素的值,通过索引访问。

sortedDictionary.Values[index] = value; // compile error

请注意,以下是不正确的,因为它是通过键而不是索引访问的。

sortedDictionary[index] = value; // incorrect

我想到了以下解决方案,但直觉告诉我它很慢。我假设通过键访问是 O(log N),通过索引访问是 O(1),但我不确定。

sortedDictionary[sortedDictionary.ElementAt(index).Key] = value;

一些背景:

我正在使用 SortedDictionary,因为我需要快速插入、删除、查找,并且能够访问相邻元素。 (即次高或次低。)效率很重要。

最佳答案

这有点权衡。

您可以使用 SortedList 并获得更快的索引查找,但您将牺牲插入速度。

引用MSDN :

...Another difference between the SortedDictionary<(Of <(TKey,
TValue>)>)
and SortedList<(Of <(TKey,
TValue>)>)
classes is that SortedList<(Of <(TKey, TValue>)>) supports efficient indexed retrieval of keys and values through the collections returned by the Keys and Values properties. It is not necessary to regenerate the lists when the properties are accessed, because the lists are just wrappers for the internal arrays of keys and values.

两者都是 SortedDictionarySortedList已实现 IDictionary ,所以我会一起获取一些测试数据和代码分析器,然后尝试两者。

如果两者都不够快,您可能需要开始考虑使用 Dictionary (快速插入、更新和键查找)并在第二个数据结构中手动维护索引。

关于c# - 设置 SortedDictionary 的第 i 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1398216/

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