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.