C++ vector::swap() 函數
vector::swap() 是 "vector" 頭文件的庫函數,用於交換向量的內容,用一個向量調用它並接受另一個向量作為參數並交換它們的內容。 (兩個向量的大小可能不同)。
注意:要使用矢量,請包括<vector>
標題。
vector::swap() 函數的語法
vector::swap(vector& v);
參數: v
– 與當前向量交換內容的另一個向量。
返回值: void
——它什麽都不返回。
例:
Input: vector<int> v1{ 10, 20, 30, 40, 50 }; vector<int> v2{ 100, 200, 300 }; //swapping content of the vectors v1.swap(v2); Output: //if we print the values v1:100 200 300 v2:10 20 30 40 50
C++程序演示vector::swap()函數的例子
//C++ STL program to demonstrate example of
//vector::erase() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector declaration
vector<int> v1{ 10, 20, 30, 40, 50 };
vector<int> v2{ 100, 200, 300 };
//printing the sizes and values of the vectors
cout << "before swap() call..." << endl;
cout << "size of v1:" << v1.size() << endl;
cout << "size of v2:" << v2.size() << endl;
cout << "v1:";
for (int x:v1)
cout << x << " ";
cout << endl;
cout << "v2:";
for (int x:v2)
cout << x << " ";
cout << endl;
//swapping the content of the vectors
v1.swap(v2);
//printing the sizes and values of the vectors
cout << "after swap() call..." << endl;
cout << "size of v1:" << v1.size() << endl;
cout << "size of v2:" << v2.size() << endl;
cout << "v1:";
for (int x:v1)
cout << x << " ";
cout << endl;
cout << "v2:";
for (int x:v2)
cout << x << " ";
cout << endl;
return 0;
}
輸出
before swap() call... size of v1:5 size of v2:3 v1:10 20 30 40 50 v2:100 200 300 after swap() call... size of v1:3 size of v2:5 v1:100 200 300 v2:10 20 30 40 50
參考:C++ vector::swap()
相關用法
- C++ vector::shrink_to_fit()用法及代碼示例
- C++ vector::size()用法及代碼示例
- C++ vector::max_size()用法及代碼示例
- C++ vector::rbegin()用法及代碼示例
- C++ vector::pop_back()用法及代碼示例
- C++ vector::crend()用法及代碼示例
- C++ vector::push_back()用法及代碼示例
- C++ vector::emplace_back用法及代碼示例
- C++ vector::at()用法及代碼示例
- C++ vector::cbegin()用法及代碼示例
- C++ vector::back()用法及代碼示例
- C++ vector::assign()用法及代碼示例
- C++ vector::begin()用法及代碼示例
- C++ vector::cend()用法及代碼示例
- C++ vector::operator[]用法及代碼示例
- C++ vector::clear()用法及代碼示例
- C++ vector::cbegin()、vector::cend()用法及代碼示例
- C++ vector::empty()用法及代碼示例
- C++ vector::front()、vector::back()用法及代碼示例
- C++ vector::at()、vector::swap()用法及代碼示例
注:本文由純淨天空篩選整理自 vector::swap() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。