Open In App

vector swap() in C++

Last Updated : 05 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, std::vector::swap() is a built-in function used to exchange the contents to two vectors of same type. This function does not copy, move or swap the individual elements, instead, it swaps the internal pointers to the dynamically allocated array of both vectors and updates the size accordingly.

Example:

C++
// C++ program to demonstrate the use of vector::swap
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v1 = {1, 2, 3};
    vector<int> v2 = {10, 20, 30};

    // Swapping contents of vec1 and vec2
    v1.swap(v2);

  	cout << "v1: ";
    for (int i : v1)
      	cout << i << " ";
  
    cout << endl << "v2: ";
    for (int i : v2)
      cout << i << " ";

    return 0;
}

Output
v1: 10 20 30 
v2: 1 2 3 

Syntax of vector::swap()

The std::vector::swap() is a member function of std::vector class defined inside <vector> header file.

v1.swap(v2);

Parameters

  • v2: Second vector to be swapped. It must be of same data type as v1.

Return Value

  • This function does not return any value.

More Examples of vector::swap()

The below examples demonstrate the behaviour and side effects of using vector::swap().

Example 1: Swapping Two Vectors of Strings

C++
// C++ program to swap two vectors of strings
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<string> v1 = {"apple", "banana", "cherry"};
    vector<string> v2 = {"orange", "kiwi"};

    // Swapping contents of v1 and v2
    v1.swap(v2);
  
    cout << "v1: ";
    for (auto s : v1)
      	cout << s << " ";
    cout << endl << "v2: ";
    for (auto s : v2)
      	cout << s << " ";

    return 0;
}

Output
v1: orange kiwi 
v2: apple banana cherry 

Example 2: Iterator Behaviour After Using vector::swap()

As std::vector::swap() function swaps just the internal pointers, the iterators to the elements of both vectors remains valid.

C++
// C++ program to demonstrate iterator behavior after
// vector::swap
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v1 = {1, 2, 3};
    vector<int> v2 = {10, 20, 30};

    // Getting iterators before swap
    auto it1 = v1.begin();
    auto it2 = v2.begin();

    // Swapping contents of v1 and v2
    v1.swap(v2);

    cout << "v1[0] (old v2): " << *it2 << endl;
    cout << "v2[0] (old v1): " << *it1;

    return 0;
}

Output
v1[0] (old v2): 10
v2[0] (old v1): 1

Difference Between std::swap() and vector::swap()

The std::swap() is a universal algorithm that can be used to swap the any two non-constant variable or objects. While the vector::swap() is used to swap the two vectors only.

Internally, when std::swap() is called for a vector, it calls the vector::swap() to perform swapping.


Next Article
Practice Tags :

Similar Reads