Board logo

標題: 【4-1】map 基礎練習 [打印本頁]

作者: 教學組    時間: 2025-2-6 20:09     標題: 【4-1】map 基礎練習

本帖最後由 教學組 於 2025-2-7 18:12 編輯

  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.     mp.insert({6, "s3"});   //若key發生重複,新的value不會取代舊的。
  15.     mp.erase(5);   //刪除鍵5
  16.     /*
  17.     for(int i=0; i<=10; i++)    //行不通
  18.         cout<<i<<": "<<mp[i]<<endl;*/

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

  22.     for(auto it=mp.begin(); it!=mp.end(); it++)
  23.         cout<<(*it).first<<": "<<(*it).second<<endl;
  24.     cout<<"-------"<<endl;

  25.     cout<<"容器中有"<<mp.size()<<"組pair"<<endl;
  26.     int t=9;
  27.     if(mp.count(t))
  28.         cout<<"鍵"<<t<<"在容器中"<<endl;
  29.     else
  30.         cout<<"鍵"<<t<<"不在容器中"<<endl;

  31.     cout<<"最前端的鍵是"<<(*mp.begin()).first<<"值是"<<(*mp.begin()).second<<endl;
  32.     cout<<"最尾端的鍵是"<<(*mp.rbegin()).first<<"值是"<<(*mp.rbegin()).second<<endl;
  33.     return 0;
  34. }
複製代碼





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