Board logo

標題: map容器 [打印本頁]

作者: 李泳霖    時間: 2023-12-27 19:45     標題: map容器

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

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

[attach]17215[/attach]
  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. }
複製代碼

作者: 林宇翔    時間: 2023-12-27 19:59

此帖僅作者可見
作者: 林宇翔    時間: 2023-12-27 20:01

此帖僅作者可見
作者: 林宇翔    時間: 2023-12-27 20:03

此帖僅作者可見
作者: 張永學    時間: 2024-2-5 14:04

此帖僅作者可見
作者: 吳孟軒    時間: 2024-8-26 19:55

此帖僅作者可見
作者: 陳人瑀    時間: 2024-8-31 16:38

此帖僅作者可見




歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/) Powered by Discuz! 7.2