What is std::vector::swap in C++?

The swap() function is defined in the header <vector>. It swaps the contents of two vectors with each other. The sizes of the two vectors may be different.

Syntax

void swap (vector& vec);

Parameters

The function takes one argument:

  • vec: A vector of the same data type with which the content will be swapped.

Return value

This function returns nothing.

The change is made directly to the vector.

Code

#include <iostream>
#include <vector>
using namespace std;
void printVec(int size, vector<char> vec)
{
for(int i = 0; i < size; i++)
{
cout << vec.at(i) << " ";
}
cout << endl;
}
int main() {
vector<char> myVec1 = {'1', '2', '3'};
vector<char> myVec2 = {'a', 'b', 'c', 'd'};
cout << "Vec1, before swap: ";
printVec(myVec1.size(), myVec1);
cout << "Vec2, before swap: ";
printVec(myVec2.size(), myVec2);
myVec1.swap(myVec2);
cout << "Vec1, after swap: ";
printVec(myVec1.size(), myVec1);
cout << "Vec2, after swap: ";
printVec(myVec2.size(), myVec2);
return 0;
}