返回列表 發帖

map容器

本帖最後由 李泳霖 於 2023-12-27 20:00 編輯

Map 就像是一個對應表
基本功能有:
[]: 得到對應的值
count: 檢查某個值是否有對應值

  1. #include <map>
  2. using namespace std;

  3. int main(){
  4.     map<string, int> m;     // 從 string 對應到 int

  5.                         // 設定對應的值
  6.     m["one"] = 1;       // "one" -> 1
  7.     m["two"] = 2;       // "two" -> 2
  8.     m["three"] = 3;     // "three" -> 3

  9.     cout << m.count("two") << endl;     // 1 -> 有對應
  10.     cout << m.count("ten") << endl;     // 0 -> 沒有對應
  11. }
複製代碼
  1. #include <map>
  2. using namespace std;

  3. int main(){
  4.     map<string, int> m;     // 從 string 對應到 int

  5.     m["one"] = 1;       // "one" -> 1
  6.     m["two"] = 2;       // "two" -> 2
  7.     m["three"] = 3;     // "three" -> 3

  8.     cout << m["one"] << endl;       // 1
  9.     cout << m["three"] << endl;     // 3
  10.     cout << m["ten"] << endl;       // 0 (無對應值)
  11. }
複製代碼
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. map<int, string> mp;
  4. //map<int, int> mp={{9,22},{1,35},{6,77}};   //給予初始值
  5. int main()
  6. {
  7.     mp[2]="t";
  8.     mp[7]="s";
  9.     mp[1]="o";
  10.     mp[5]="f";
  11.     mp[6]="s";
  12.     mp[9]="n";
  13.     mp[6]="s2";   //若key發生重複,新的value會取代舊的。
  14.     /*
  15.     for(int i=0; i<=10; i++)
  16.         cout<<i<<": "<<mp[i]<<endl;*/

  17.     for(auto p: mp)   //從map裡撈出的每一個成員都是pair
  18.         cout<<p.first<<": "<<p.second<<endl;

  19.     return 0;
  20. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊
istak.teach2@gmail.com

此帖僅作者可見
羽毛神在此

TOP

此帖僅作者可見
羽毛神在此

TOP

此帖僅作者可見
羽毛神在此

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

返回列表