? 在C++語言中,我們經(jīng)常使用到map集合來存儲(chǔ) key-value 類型的數(shù)據(jù)。這里將常用到的map集合操作方法整理出來。
創(chuàng)新互聯(lián)建站堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設(shè)公司、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的滕州網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!1. map集合的初始化這里列舉三種初始化的方法:
//初始化不設(shè)置參數(shù)
maptempMap1;
//初始化設(shè)置參數(shù)
maptempMap2 = { {"1" , "temp21"},{"2" , "temp22"} };
//初始化設(shè)置參數(shù) 使用 pair 函數(shù)指定存儲(chǔ)的數(shù)據(jù)類型
maptempMap3 = { pair("1" , "temp21"), pair("2","temp22")};
2. map集合添加數(shù)據(jù)使用 insert() 函數(shù)向map集合中添加相應(yīng)的數(shù)據(jù)
//直接添加數(shù)據(jù) - 添加單個(gè)數(shù)據(jù)
tempMap1["1"] = "數(shù)據(jù)1";
//添加多個(gè)數(shù)據(jù) - 添加單個(gè)數(shù)據(jù)
tempMap1.insert({ {"2","數(shù)據(jù)2"},{"3","數(shù)據(jù)3"} });
//使用 pari 函數(shù)指定存儲(chǔ)的數(shù)據(jù)類型
tempMap1.insert(pair("4", "數(shù)據(jù)4"));
3. map集合的遍歷使用迭代器?iterator 進(jìn)行map集合的遍歷?
例:
//直接添加數(shù)據(jù) - 添加單個(gè)數(shù)據(jù)
tempMap1["1"] = "數(shù)據(jù)1";
//添加多個(gè)數(shù)據(jù) - 添加單個(gè)數(shù)據(jù)
tempMap1.insert({ {"2","數(shù)據(jù)2"},{"3","數(shù)據(jù)3"} });
//使用 pari 函數(shù)指定存儲(chǔ)的數(shù)據(jù)類型
tempMap1.insert(pair("4", "數(shù)據(jù)4"));
for (map::iterator iter = tempMap1.begin(); iter != tempMap1.end(); ++iter) {
string strKey = iter->first;
string strValue = iter->second;
cout<< "strKey = "<< strKey<< " strValue = "<< strValue<< "\n";
}
輸出結(jié)果:?
???????
優(yōu)化:
針對(duì)例子中的for循環(huán),map
for (auto iter = tempMap1.begin(); iter != tempMap1.end(); ++iter) {
string strKey = iter->first;
string strValue = iter->second;
cout<< "strKey = "<< strKey<< " strValue = "<< strValue<< "\n";
}
4. map集合中數(shù)據(jù)的修改map集合中沒有特定的修改數(shù)據(jù)的方法,因?yàn)樵诩现幸粋€(gè)key只能對(duì)應(yīng)一個(gè)value,在map集合中后添加相同的key,會(huì)覆蓋已有的key-value數(shù)據(jù),達(dá)到修改數(shù)據(jù)的效果。
修改的方法就是重新添加相同的key,修改value
5. map集合刪除數(shù)據(jù)
? 刪除數(shù)據(jù)可以使用earse函數(shù)? 入?yún)閗ey值
例:
//刪除 key = "1" 的數(shù)據(jù)
tempMap1.erase("1");
6. map集合清空
? 清空數(shù)據(jù)使用 clear 函數(shù)
例:
//清空map集合
tempMap1.clear();
? 以上就是總結(jié)的方法,希望能夠?qū)δ阌袔椭?/p>
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧
網(wǎng)站欄目:c++中map集合的基本使用方法添加、刪除、修改、清空、遍歷-創(chuàng)新互聯(lián)
路徑分享:http://jinyejixie.com/article8/cspjop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、搜索引擎優(yōu)化、ChatGPT、網(wǎng)站建設(shè)、App開發(fā)、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容