English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This function is used to swap the specified elements in two vectors (vector).
two vectors (vector) v1and v2. Syntax is:
v1.swap(v2);
v2: v2is a vector (vector) whose values will be swapped with another vector (vector).
It does not return any value.
Let's look at a simple example.
#include<iostream> #include<vector> using namespace std; int main() { vector<int> v1={1,2,3,4,5}; vector<int> v2={6,7,8,9,10}; cout << "Before swapping, v"1The element is : ";" for (int i = 0; i < v1.size();i++) cout << v1[i] << " "; cout << '\n'; cout << "Before swapping, v"2The element is : ";" for(int i = 0; i < v2.size();i++) cout << v2[i] << " "; cout << '\n'; v1.swap(v2); cout << "After swapping, v1The elements are:" for(int i = 0; i < v1.size();i++) cout << v1[i] << " "; cout << '\n'; cout << "After swapping, v2The elements are:" for(int i = 0; i < v2.size();i++) cout << v2[i] << " "; return 0; }
Output:
Before swapping, v1The elements are:1 2 3 4 5 Before swapping, v2The elements are:6 7 8 9 10 After swapping, v1The elements are:6 7 8 9 10 After swapping, v2The elements are:1 2 3 4 5
In this example, the swap() function will swap the elements of vector (vector) v1The elements with vector (vector) v2Swap.