On Feb 20, 12:10 am, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
Stefan Istrate wrote:
How can I find the k-th position in a STL set? I want to do
this in O(logN) time, where N is the dimension of the set.
I don't think it's possible. The only way I know (without
going into the implementation) is to 'advance' the 'begin()'
iterator 'k' times. That's O(k) time, most likely amortized.
To make it better you have to rely on a certain implementation
of the list, which isn't specified (although could be deduced,
probably).
From time to time, it is suggested to use a sorted vector
instead of a set. Depending on what he's doing with it, it may
even be faster as well. Generally, insertions and deletions
are slower, lookups, using lower_bound, are faster. But there
are exceptions to even this rule. And of course, finding the
nth element is clearly O(1), with a very, very small constant
term as well:-).
the collection in a set and then copy it into a vector. The
copying is O(N). Of course this means huge savings iff the
"formation" (insertions) happens before the "use" (lookups).
that can gain significantly.