C++ STL 中的 map::at() 和 map::swap()


在本文中,我們將討論 C++ STL 中 map::at() 和 map::swap() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

Map 是關聯容器,它可以方便地以特定順序儲存由鍵值對組成的元素。在 map 容器中,資料內部總是透過其關聯的鍵進行排序。map 容器中的值透過其唯一的鍵進行訪問。

什麼是 map::at()?

map::at() 函式是 C++ STL 中的內建函式,它在 `` 標頭檔案中定義。 header file. at() is used to access a specific element of the associated map container. This function returns a reference to the specific value which is associated with the key.

如果鍵與 map 容器中的任何鍵都不匹配,則該函式會丟擲 out_of_range 異常。

語法

map_name.at(key& k);

引數

該函式接受一個引數,即:

  • k − 這是我們要引用的鍵。

返回值

此函式返回對與我們正在查詢的鍵 k 關聯的值的引用。

示例

輸入

std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b, 20});
mymap.insert({‘c, 30});
mymap.at(‘b’);

輸出

b:20

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   TP_2[5] = 50;
   TP_2[6] = 60;
   TP_2[7] = 70;
   cout<<"Elements at TP_1[1] = "<< TP_1.at(1) << endl;
   cout<<"Elements at TP_1[2] = "<< TP_1.at(2) << endl;
   cout<<"Elements at TP_1[3] = "<< TP_1.at(3) << endl;
   cout<<"\nElements at TP_2[7] = "<< TP_2.at(7) << endl;
   cout<<"Elements at TP_2[5] = "<< TP_2.at(5) << endl;
   return 0;
}

輸出

Elements at TP_1[1] = 10
Elements at TP_1[2] = 20
Elements at TP_1[3] = 30
Elements at TP_1[7] = 70
Elements at TP_1[5] = 50

什麼是 map::swap()?

map::swap() 函式是 C++ STL 中的內建函式,它在 `` 標頭檔案中定義。swap() 用於交換兩個 map 容器的內容。此函式交換兩個 map 容器的值,而不管兩個 map 容器的大小如何。

當呼叫此函式時,它會接收另一個 map 容器作為引數,並將內容與關聯的容器交換。

語法

map_name.swap(map& map_name2);

引數

該函式接受一個引數,即:

  • map_name2 − 這是另一個 map 容器的物件,我們希望將其資料與關聯的 map 容器交換。

返回值

此函式不返回值。

示例

輸入

std::map<int> odd, eve;
odd.insert({‘a’, 1});
odd.insert({‘b’, 3});
odd.insert({‘c’, 5});
eve.insert({‘d’, 2});
eve.insert({‘e’, 4});
eve.insert({‘f’, 6});
odd.swap(eve);

輸出

Odd: d: 2 e:4 f:6
Eve: a:1 b:3 c:5

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   TP_2[5] = 50;
   TP_2[6] = 60;
   TP_2[7] = 70;
   swap(TP_1, TP_2);
   cout<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   cout << "Elements of TP_2 after swap:\n"<< "\tKEY\tELEMENT\n";
   for (auto i = TP_2.begin(); i!= TP_2.end(); i++) {
      cout << "\t" << i->first << "\t" << i->second << '\n';
   }
   return 0;
}

輸出

Elements of TP_1 after swap:
KEY    ELEMENT
5       50
6       60
7       70
Elements of TP_2 after swap:
KEY    ELEMENT
1       10
2       20
3       30
4       40

更新於:2020年4月15日

496 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告