In the C++ standard page 472
It's much better to cite section numbers or (better still) section names
-- page numbers change from one version of the standard to the next, but
the section names remain much closer to constant.
it says that you can construct a std::set
in linear time if the constructor gets a sorted sequence of elements.
But how is this possible when insert takes logarithmic time? Should the
time not be nlgn where n is the number of elements?
Doing it with random access iterators is (mostly) pretty simple. You
basically ignore the fact that you're working with a red-black tree (or
AVL tree) and instead just construct a perfectly balanced tree -- take
the median item in the input sequence, and make that your root. This
leaves two halves of the input, which you recursively insert as the left
and right sub-trees of the current node.
This means you never re-balance the tree during creation (because you're
creating it as close to perfectly balanced as possible given the number
of nodes), and each node you insert is always a direct descendent of the
current node, so you never have to do a Log(N) traversal to find where
to insert a node.
With Input Iterators, this gets a bit ugly -- doing this in linear time
requires figuring the distance (and median item) in constant time. You
could temporarily copy from the input sequence to a vector or deque, but
that would rarely be worthwhile. In theory I believe this should be a
win for a sufficiently large collection, but by the time it gets large
enough, the space for the temporary copy would probably be prohibitive.