I want to store some values in a balanced binary search tree using C#. I looked through the collections in the generics namespace and I haven't found an equivalent of the stl set.
What generic collection can I use? (I don't want to store key/value pairs... just values.)
You could use an HashSet
The
HashSet<T>
class provides high performance set operations. A set is a collection that contains no duplicate elements , and whose elements are in no particular order.
The capacity of a HashSet<T>
object is the number of elements that the object can hold. A HashSet<T>
object's capacity automatically increases as elements are added to the object.
If you require sorted set, use SortedDictionary<T,U>
. This is implemented using a binary search tree. Admittedly, you will be using 64-bits per entry because you are storing a key-value pair underneath. You can write a wrapper around it like this:
class Set<T> : SortedDictionary<T, bool> { public void Add(T item) { this.Add(item, true); } }
If you don't require a sorted set, use HashSet<T>
.
Otherwise, check out C5 Generic Collection Library . In particular TreeSet<T>
. It is a red-black tree and only stores the values.
Try RedBlackTree.NET . It's in VB but I think it can be easily converted to C#.
And I believe some of the collection type actually uses a red-black tree internally . So you might want to decompile the framework itself and look around for some clues.
I don't think a binary tree can be replaced by a HashSet. Their performance characteristics are different, roughly:
HashSet - O(1) lookup (n) search
Binary search tree - O(log n) lookup O(log n) search
If you want to store the values and later perform a search, you will want to be using a binary tree instead of a HashSet.
HashSet, but HashSet isn't available in version 2.0 of the framework. If you need something for 2.0 then use Dictionary, and specify a dummy type (eg object, int, or bool) for which you supply a dummy value (eg null, 0, or false) as the second/value parameter (ie use the Dictionary as a set of keys without caring about the associated values).
我知道这个问题很老,但对于 .NET Framework 4.0 及更高版本,请使用SortedSet<T>
或ImmutableSortedSet<T>
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.