Swampmonster wrote:
Clark S. Cox III wrote: On 2005-06-16 13:21:41 -0400, Ron Natalie <ro*@spamcop.net> said:
tuvok wrote:
I'm currently using the 2nd version, but was looking for a faster way.
v1 does not need to be intact after the transfer. Best would be if it
shrinks to 0 elems without calling any item dtor. Is this possible?
Then swap is your answer. Many implementations specialize swap
to move the vector internals between the two objects. You
move the internal array from v1 to v2 and v2's empty array
into v1.
There's virtually no other way to implement swap for vectors,
considering that it is required to be constant time.
vector::swap is required to run in constant time, because containers
may only provide a swap function if it can run in constant time.
std::swap<T> _is not_ required to run in constant time for arbitrary T.
Since vector::swap is a simple member function and therefor no
specialization I strongly assume that std::swap was ment.
Btw.: vector::swap can only run in constant time if the allocator
is equal (i.e. operator == on the 2 stored allocators returns true).
Though if one uses the standard allocater this should not be a
problem.
It's a given that the allocators of both vectors will be of the same
type; since the allocator employed by the vector is part of the
vector's type and both std:: and vector::swap require identical types.
The point about the different swap() routines is a good one. Since it's
known that calling vector::swap() is the fastest way to transfer the
contents of one vector to another, why call std::swap() and hope that
it calls vector::swap() (it should) and not buy some peace of mind by
calling vector::swap() directly?
After all the last function one would want to call to perform the
transfer would be the general swap implementation. If the general case
std::swap() were somehow called it would be twice as slow as a simple
assignment; and the simple assignment is already too slow. As has been
pointed out vector::swap() executes in constant time regardless of the
size of the vectors, whereas an assignment operation slows as the
vector grows... [the C++ poetry has been added for cultural enrichment.
Please do not send requests for addition poems in this genre. It will
be necessary to wait for my six volume set of C++ poetry due some time
in the fall.. :-) ].
Greg