In this C++ tutorial, you will learn about vector::swap() function, its syntax, and how to use this function to exchange the elements between two vectors, with example programs.

C++ Vector swap() function

swap() function exchanges or swaps the elements of two vectors.

Syntax

The syntax of swap() function is

</>
Copy
void swap( vector<Type, Allocator>& right );

where right is the vector with whose the elements of this vector are to be exchanged.

Example

In the following C++ program, we define two vectors: vec1 and vec2. We shall swap the elements of these two vectors using swap() function.

C++ Program

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> vec1{ "apple", "banana", "cherry" };
    vector<string> vec2{ "mango", "orange"};
    
    vec1.swap(vec2);
    
    cout << "Vector 1\n--------\n";
    for ( string x: vec1 ){
        cout << x << endl;
    }
    
    cout << "\nVector 2\n--------\n";
    for ( string x: vec2 ){
        cout << x << endl;
    }
}

Output

Vector 1
--------
mango
orange

Vector 2
--------
apple
banana
cherry
Program ended with exit code: 0

The contents of the two vectors are interchanged/swapped.

Conclusion

In this C++ Tutorial, we learned the syntax of swap() function, and how to use this swap() function to exchange elements of two vectors.