diference btw std::swap and std::vector::swap

I came to know that vector::swap has O(1) time complexity , while when std::swap is applied on vectors the time complexity is linear. Can someone explain how the complexity of std::vector::swap is constant.
EX
vector a={2,3};
vector b={4,5};
a.swap(b) is of contant time complexity how??

3 Likes

Because std::vector::swap swaps pointers and doesn’t invoke any move, copy, or swap operations on individual elements.

3 Likes

std::swap

The behavior of this function template is equivalent to:

template <class T> void swap ( T& a, T& b ) {
  T c(a); a=b; b=c;
}

For a vector its time complexity is linear as it performs a swap operation per element.

std::vector::swap

This is an overload of the above generic algorithm that improves its performance by mutually transferring ownership over their assets to the other container (i.e., the containers exchange references to their data, without actually performing any element copy or movement).

Thus, whatever may be the size of the vector this function just swaps the address of both the vector,which is performed in constant time.

I hope I was clear enough.

5 Likes

Thanks for the answer but can you please tell how we can imitate vector::swap using our own custom function. I mean what if I am not allowed to use the std::vector::swap but instead write my own customswap() for swapping two vectors;

1 Like

Yes, we can implement vector::swap using our own custom function.

void customswap(vector& a, vector& b){
vector c=a;
a=b;
b=c;
}
and call this by,
customswap(a,b);
This will do the required task.

1 Like