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


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


multimap::swap()是C++ STL中的內置函數,它交換兩個多圖容器。調用swap()函數後,multimap1的內容在multimap2中,multimap2的內容在multimap1中。

用法:

multimap1_name.swap(multimap2_name)

參數:此函數接受一個要與multimap1_name交換的參數,


返回值:該函數不返回任何內容。

// C++ function for illustration 
// multiset::swap() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // initialize container 
    multimap<int, int> mp1, mp2; 
  
    // insert elements in random order 
    mp1.insert({ 2, 30 }); 
    mp1.insert({ 1, 40 }); 
  
    mp2.insert({ 10, 60 }); 
    mp2.insert({ 9, 20 }); 
  
    cout << "\nThe multimap1 before applying swap() is : \n"; 
    cout << "KEY\tELEMENT\n"; 
    for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) { 
        cout << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    cout << "\nThe multimap2 before applying swap() is : \n"; 
    cout << "KEY\tELEMENT\n"; 
    for (auto itr = mp2.begin(); itr != mp2.end(); ++itr) { 
        cout << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    // performs swap operation of two multimap 
    mp1.swap(mp2); 
  
    cout << "\nThe multimap1 after applying swap() is : \n"; 
    cout << "KEY\tELEMENT\n"; 
    for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) { 
        cout << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    cout << "\nThe multimap2 after applying swap() is : \n"; 
    cout << "KEY\tELEMENT\n"; 
    for (auto itr = mp2.begin(); itr != mp2.end(); ++itr) { 
        cout << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    return 0; 
}


相關用法


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