stl swap函数_C ++ STL | vector :: swap()函数与示例
stl swap函數
C ++ STL vector :: swap()函數 (C++ STL vector::swap() function)
vector::swap() function is used to swap/exchange the content of two vectors with the same type, their sizes may differ.
vector :: swap()函數用于交換/交換相同類型的兩個向量的內容,它們的大小可能不同。
The contents of vector1 are exchanged with the content of vector2. Vectors must be of the same type i.e. either both of them are of type int, string, long, etc.
vector1的內容與vector2的內容交換。 向量必須具有相同的類型,即兩個向量均為int,string,long等類型。
This is not necessary that both of the vectors must have the same size i.e. size of both the vectors may differ from each other.
兩個矢量必須具有相同的大小是不必要的,即,兩個矢量的大小可以彼此不同。
Note: Both the containers/vectors are modified after the call of this function.
注意:調用此函數后,兩個容器/向量均被修改。
Syntax of vector::swap() function
vector :: swap()函數的語法
vector1.swap(vector2);Parameter(s): vector2 – another vector with that we have to swap the content of first vector vector1.
參數: vector2 –與另一個向量我們必須交換第一個向量vector1的內容。
Return value: void – it returns nothing.
返回值: void –不返回任何內容。
Time Complexity: O(1) i.e constant order
時間復雜度:O(1),即恒定階數
Example:
例:
Input:vector<int> vector1{ 1, 2, 3, 4, 5 };vector<int> vector2{ 6, 7, 8, 9, 10 };Function call:vector1.swap(vector2);Output:Vector1: 1 2 3 4 5Vector2: 6 7 8 9 10 After swapping...Vector1: 6 7 8 9 10 Vector2: 1 2 3 4 5C ++程序演示vector :: swap()函數的示例 (C++ program to demonstrate example of vector::swap() function)
#include <iostream> #include <vector> using namespace std;int main() {vector<int> vector1{ 1, 2, 3, 4, 5 };vector<int> vector2{ 6, 7, 8, 9, 10 };// Before Swapping vector-1 and vector-2cout << "Vector 1" << endl;for (auto i : vector1)cout << i << " ";cout << "\n";cout << "Vector 2" << endl;for (auto i : vector2)cout << i << " ";cout << "\n";// Swapping vector-1 and vector-2vector1.swap(vector2);// After swapping vector-1 and vector-2cout << "Vector 1" << endl;for (auto i : vector1)cout << i << " ";cout << "\n";cout << "Vector 2" << endl;for (auto i : vector2)cout << i << " ";return 0; }Output
輸出量
Vector 1 1 2 3 4 5 Vector 2 6 7 8 9 10 Vector 1 6 7 8 9 10 Vector 2 1 2 3 4 5翻譯自: https://www.includehelp.com/stl/vector-swap-method-with-example.aspx
stl swap函數
總結
以上是生活随笔為你收集整理的stl swap函数_C ++ STL | vector :: swap()函数与示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 获取service_Java
- 下一篇: ruby hash添加数据_如何在Rub