stl swap函数_C ++ STL | vector :: swap()函数与示例
stl swap函數(shù)
C ++ STL vector :: swap()函數(shù) (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()函數(shù)用于交換/交換相同類型的兩個(gè)向量的內(nèi)容,它們的大小可能不同。
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的內(nèi)容與vector2的內(nèi)容交換。 向量必須具有相同的類型,即兩個(gè)向量均為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.
兩個(gè)矢量必須具有相同的大小是不必要的,即,兩個(gè)矢量的大小可以彼此不同。
Note: Both the containers/vectors are modified after the call of this function.
注意:調(diào)用此函數(shù)后,兩個(gè)容器/向量均被修改。
Syntax of vector::swap() function
vector :: swap()函數(shù)的語(yǔ)法
vector1.swap(vector2);Parameter(s): vector2 – another vector with that we have to swap the content of first vector vector1.
參數(shù): vector2 –與另一個(gè)向量我們必須交換第一個(gè)向量vector1的內(nèi)容。
Return value: void – it returns nothing.
返回值: void –不返回任何內(nèi)容。
Time Complexity: O(1) i.e constant order
時(shí)間復(fù)雜度:O(1),即恒定階數(shù)
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()函數(shù)的示例 (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函數(shù)
總結(jié)
以上是生活随笔為你收集整理的stl swap函数_C ++ STL | vector :: swap()函数与示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 获取service_Java
- 下一篇: ruby hash添加数据_如何在Rub