For example:
v1 = {1,2,3}, v2 = {4,5};
swap(v1, v2);
now v1 = {4,5}
, v2 = {1,2,3}
I think it should be very fast with no regards of the length of these two vectors right? It's just swapping pointers?
I think it should be very fast with no regards of the length of these two vectors right?
Yes. std::swap
for std::vector
's complexity is guaranteed to be constant time by the stardard:
23.3.6.3$10,11 [vector.capacity](bold by me):
void swap(vector& x);
Effects: Exchanges the contents and capacity() of *this with that of x.
Complexity: Constant time.
And by $23.3.6.6/1 [vector.special], std::swap
for std::vector
is Specialized as:
template <class T, class Allocator>
void swap(vector<T,Allocator>& x, vector<T,Allocator>& y);
Effects:x.swap(y);
Here're some more explanations: std::vector::swap and std::swap(std::vector)
Exchanges the contents of the container with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Complexity : Constant.
It's just swapping pointers?
Basically, it depenes on the implementation of the STL you're using, but it is the most common way to achieve it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With