當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_multiset swap()用法及代碼示例


unordered_multiset::swap()是C++ STL中的內置函數,該函數交換兩個unordered_multiset的內容
容器。

注意:兩個容器應具有相同類型的元素。容器的尺寸可能會有所不同。

用法:


unordered_multiset1.swap(unordered_multiset2);

參數:該函數僅接受一個強製參數,即unordered_multiset2,通過該參數可以進行unordered_multiset1的交換。

返回值:它不返回任何值。

以下示例程序旨在說明上述函數。

示例1:

// C++ program to illustrate 
// unordered_multiset::swap() 
#include <iostream> 
#include <string> 
#include <unordered_set> 
  
using namespace std; 
  
// Function to display the contents of multiset s. 
void display(unordered_multiset<int> s) 
{ 
    for (auto it = s.begin(); it != s.end(); it++) 
        cout << *it<<" "; 
    cout<<"\n";     
} 
  
int main() 
{ 
    // Declaration 
    unordered_multiset<int> s1, s2; 
  
    // initializing both multisets(sizes are different) 
    s1 = { 1, 2, 3, 4 }; 
    s2 = { 10, 20, 30, 40, 50 }; 
  
    // diplaying initial values 
    cout << "Initial values of s1 are: \n"; 
    display(s1); 
    cout << endl; 
  
    cout << "Initial values of s2 are: \n"; 
    display(s2); 
    cout << endl; 
      
    // swapping the values 
    s1.swap(s2); 
  
    // display final values 
    cout << "Final values of s1 are: \n"; 
    display(s1); 
    cout << endl; 
  
    cout << "Final values of s2 are: \n"; 
    display(s2); 
  
    return 0; 
}
輸出:
Initial values of s1 are: 
4 3 2 1 

Initial values of s2 are: 
50 40 30 20 10 

Final values of s1 are: 
50 40 30 20 10 

Final values of s2 are: 
4 3 2 1

示例2:

// C++ program to illustrate 
// unordered_multiset::swap() 
#include <iostream> 
#include <string> 
#include <unordered_set> 
  
using namespace std; 
  
// Function to display the contents of multiset s 
void display(unordered_multiset<string> s)  
{ 
    for (auto it = s.begin(); it != s.end(); it++) 
        cout << *it << " "; 
    cout<<endl; 
} 
  
int main() 
{ 
    // Declaration 
    unordered_multiset<string> s1, s2;  
  
    // Initializing both multisets(sizes are different) 
    s1 = { "Geeks", "for", "Geeks" }; 
    s2 = { "Computer", "Science", "Portal", "for", "Geeks" }; 
  
    // Diplaying initial values 
    cout << "Initial values of s1 are: \n"; 
    display(s1); 
    cout << endl; 
  
    cout << "Initial values of s2 are: \n"; 
    display(s2); 
    cout << endl; 
      
    // Swapping 
    s1.swap(s2); 
  
    // Display final values 
    cout << "Final values of s1 are: \n"; 
    display(s1); 
    cout << endl; 
  
    cout << "Final values of s2 are: \n"; 
    display(s2); 
      
    return 0; 
}
輸出:
Initial values of s1 are: 
for Geeks Geeks 

Initial values of s2 are: 
Geeks for Portal Science Computer 

Final values of s1 are: 
Geeks for Portal Science Computer 

Final values of s2 are: 
for Geeks Geeks


相關用法


注:本文由純淨天空篩選整理自Kushagra7744大神的英文原創作品 unordered_multiset swap() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。