📜  C++ STL中的unordered_multiset swap()函数

📅  最后修改于: 2021-05-30 04:44:53             🧑  作者: Mango

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 
#include 
#include 
  
using namespace std;
  
// Function to display the contents of multiset s.
void display(unordered_multiset s)
{
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it<<" ";
    cout<<"\n";    
}
  
int main()
{
    // Declaration
    unordered_multiset 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 
#include 
#include 
  
using namespace std;
  
// Function to display the contents of multiset s
void display(unordered_multiset s) 
{
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
    cout< 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”