Difference between std::swap and std::vector::swap

• Difficulty Level : Basic
• Last Updated : 19 Jul, 2021

The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.
Below are some major key differences between std::swap and std::vector::swap,

In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance. For consistency, it may be better to use the std::swap.

Program 1: To illustrate swapping of two vectors using std::swap().

CPP

 // CPP program to illustrate swapping// of two vectors using std::swap() #include using namespace std; int main(){    vector v1 = { 1, 2, 3 };    vector v2 = { 4, 5, 6 };     // swapping the above two vectors    // by traversing and swapping each element    for (int i = 0; i < 3; i++) {        swap(v1[i], v2[i]);    }     // print vector v1    cout << "Vector v1 = ";    for (int i = 0; i < 3; i++) {        cout << v1[i] << " ";    }     // print vector v2    cout << "\nVector v2 = ";    for (int i = 0; i < 3; i++) {        cout << v2[i] << " ";    }     return 0;}
Output:
Vector v1 = 4 5 6
Vector v2 = 1 2 3

Program 2: To illustrate swapping of two vectors using std::vector::swap().

CPP

 // CPP program to illustrate swapping// of two vectors using std::vector::swap() #include using namespace std; int main(){    vector v1 = { 1, 2, 3 };    vector v2 = { 4, 5, 6 };     // swapping the above two vectors    // using std::vector::swap    v1.swap(v2);     // print vector v1    cout << "Vector v1 = ";    for (int i = 0; i < 3; i++) {        cout << v1[i] << " ";    }     // print vector v2    cout << "\nVector v2 = ";    for (int i = 0; i < 3; i++) {        cout << v2[i] << " ";    }     return 0;}
Output:
Vector v1 = 4 5 6
Vector v2 = 1 2 3

My Personal Notes arrow_drop_up