標題:
【4-1】map 基礎練習
[打印本頁]
作者:
教學組
時間:
2025-2-6 20:09
標題:
【4-1】map 基礎練習
本帖最後由 教學組 於 2025-2-7 18:12 編輯
#include<bits/stdc++.h>
using namespace std;
map<int, string> mp;
//map<int, int> mp={{9,22},{1,35},{6,77}}; //給予初始值
int main()
{
mp[2]="t";
mp[7]="s";
mp[1]="o";
mp[5]="f";
mp[6]="s";
mp[9]="n";
mp[6]="s2"; //若key發生重複,新的value會取代舊的。
mp.insert({6, "s3"}); //若key發生重複,新的value不會取代舊的。
mp.erase(5); //刪除鍵5
/*
for(int i=0; i<=10; i++) //行不通
cout<<i<<": "<<mp[i]<<endl;*/
for(auto p: mp) //從map裡撈出的每一個成員都是pair
cout<<p.first<<": "<<p.second<<endl;
cout<<"-------"<<endl;
for(auto it=mp.begin(); it!=mp.end(); it++)
cout<<(*it).first<<": "<<(*it).second<<endl;
cout<<"-------"<<endl;
cout<<"容器中有"<<mp.size()<<"組pair"<<endl;
int t=9;
if(mp.count(t))
cout<<"鍵"<<t<<"在容器中"<<endl;
else
cout<<"鍵"<<t<<"不在容器中"<<endl;
cout<<"最前端的鍵是"<<(*mp.begin()).first<<"值是"<<(*mp.begin()).second<<endl;
cout<<"最尾端的鍵是"<<(*mp.rbegin()).first<<"值是"<<(*mp.rbegin()).second<<endl;
return 0;
}
複製代碼
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://www.istak.org.tw/seed/)
Powered by Discuz! 7.2