Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two entire vectors/queue/stack time cost?

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?

like image 497
Arch1tect Avatar asked Dec 19 '22 02:12

Arch1tect


1 Answers

  1. 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.

  1. 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.

like image 118
songyuanyao Avatar answered Jan 03 '23 21:01

songyuanyao