I’m looking for a data structure to hold an unordered collection of unique elements, which would support the following operations
- insertions/deletions of elements anywhere in the collection
- querying if an element is present
- access to a random element
Naively, 1 and 2 suggest using an associative container, e.g. unordered_set, but then 3 is linear in number of elements. Using a random access container, e.g. vector, makes 3 easy, 1 can be done in O(1), but then 2 is again O(N).
The question is if there’s a known way around this linear complexity?
EDIT: By a random element in 3 I mean: given an arbitrary ordering of N elements, retrieve an element number j where j is between 0 and N-1. For an std::vector it’s just subscripting, for an std::list or an std::set it’s incrementing the list/set iterator j times starting from begin() etc.
I have been looking for such a data structure for a long time.
Recently, I found quite promising library which has all the functionality that you are looking for.
See the cntree::set with random access in O(log n).
here is the link.
http://dl.dropbox.com/u/8437476/works/countertree/index.html
Although it seems to be under development, I see it is quite usable.