C++ 笔记(24)— STL map 类(map实例化、插入、查找、删除)
1. STL 映射類(lèi)簡(jiǎn)介
map 和 multimap 是鍵-值對(duì)容器,支持根據(jù)鍵進(jìn)行查找,區(qū)別在于,后者能夠存儲(chǔ)重復(fù)的鍵,而前者只能存儲(chǔ)唯一的鍵。
為了實(shí)現(xiàn)快速查找, STL map 和 multimap 的內(nèi)部結(jié)構(gòu)看起來(lái)像棵二叉樹(shù)。這意味著在 map 或multimap 中插入元素時(shí)將進(jìn)行排序;還意味著不像 vector 那樣可以使用其他元素替換給定位置的元素,位于 map 中特定位置的元素不能替換為值不同的新元素,這是因?yàn)?map 將把新元素同二叉樹(shù)中的其他元素進(jìn)行比較,進(jìn)而將它放在其他位置。
要使用 STL map 或 multimap 類(lèi),需要包含頭文件 <map> :
#include <map>
2. STL map 和 multimap 的基本操作
STL map 和 multimap 都是模板類(lèi),要使用其成員函數(shù),必須先實(shí)例化。
2.1 實(shí)例化 std::map 和 std::multimap
要實(shí)例化將整數(shù)用作鍵、將字符串用作值的 map 或 multimap ,必須具體化模板類(lèi) std::map 或std::multimap 。
實(shí)例化模板類(lèi) map 時(shí),需要指定鍵和值的類(lèi)型以及可選的謂詞(它幫助 map 類(lèi)對(duì)插入的元素進(jìn)行排序)。因此,典型的 map 實(shí)例化語(yǔ)法如下:
#include <map>
using namespace std;
...
map <keyType, valueType, Predicate=std::less <keyType>> mapObj;
multimap <keyType, valueType, Predicate=std::less <keyType>> mmapObj;
第三個(gè)模板參數(shù)是可選的。如果您值指定了鍵和值的類(lèi)型,而省略了第三個(gè)模板參數(shù), std::map 和 std::multimap 將把 std::less<> 用作排序標(biāo)準(zhǔn),這將元素按升序排列。因此,將整數(shù)映射到字符串的 map 或 multimap 類(lèi)似于下面這樣:
std::map<int, string> mapIntToStr;
std::multimap<int, string> mmapIntToStr;
實(shí)例化示例:
int main ()
{using namespace std;// map and multimap key of type int to value of type stringmap<int, string> a;multimap<int, string> ma;// map and multimap constructed as a copy of anothermap<int, string> b(a);multimap<int, string> mb(ma);// map and multimap constructed given a part of another map or multimapmap<int, string> c(a.cbegin(), a.cend());multimap<int, string> mc(ma.cbegin(),ma.cend());return 0;
}
2.2 在 STL map 或 multimap 中插入元素
map 和 multimap 的大多數(shù)函數(shù)的用法類(lèi)似,它們接受類(lèi)似的參數(shù),返回類(lèi)型也類(lèi)似。例如,要在這兩種容器中插入元素,都可使用成員函數(shù) insert :
using namespace std;
map<int, string> d;
// insert pair of key and value using make_pair function
d.insert (make_pair (-1, "Minus One"));
鑒于這兩種容器包含的元素都是鍵-值對(duì),因此也可直接使用 std::pair 來(lái)指定要插入的鍵和值:
d.insert (pair <int, string>(1000, "One Thousand"));
另外,還可使用類(lèi)似于數(shù)組的語(yǔ)法進(jìn)行插入。是由下標(biāo)運(yùn)算符 [] 支持的:
d[1000000] = "One Million";
還可使用 map 來(lái)實(shí)例化 multimap :
multimap<int, std::string> md(d.cbegin(), d.cend());
插入代碼示例:
#include <map>
#include <iostream>
#include <string>using namespace std;// 使用 typedef 指定別名,方便閱讀
typedef map<int, string> MAP_INT_STRING;
typedef multimap<int, string> MMAP_INT_STRING;// 使用迭代器來(lái)訪問(wèn)表示鍵的 first 以及表示值的second
template <typename T>
void DisplayContents (const T& cont)
{for (auto element = cont.cbegin(); element != cont.cend(); ++ element){cout << element->first << " -> " << element->second << endl;}cout << endl;
}int main (){MAP_INT_STRING mapIntToStr;// 使用 value_type 插入鍵值對(duì)mapIntToStr.insert(MAP_INT_STRING::value_type (3, "Three"));// 使用 make_pair 函數(shù)插入鍵值對(duì)mapIntToStr.insert(make_pair (-1, "Minus One"));// 直接使用 pair 對(duì)象插入函數(shù)mapIntToStr.insert(pair<int, string>(1000, "One Thousand"));// 使用數(shù)組方式插入鍵值對(duì)mapIntToStr[1000000] = "One Million";cout << "The map contains " << mapIntToStr.size ();cout << " key-value pairs. They are: " << endl;DisplayContents(mapIntToStr);// instantiate a multimap that is a copy of a mapMMAP_INT_STRING mmapIntToStr(mapIntToStr.cbegin(), mapIntToStr.cend());// The insert function works the same way for multimap too// A multimap can store duplicates - insert a duplicatemmapIntToStr.insert (make_pair (1000, "Thousand"));cout << endl << "The multimap contains " << mmapIntToStr.size();cout << " key-value pairs. They are: " << endl;cout << "The elements in the multimap are: " << endl;DisplayContents(mmapIntToStr);// The multimap can return number of pairs with same keycout << "The number of pairs in the multimap with 1000 as their key: "<< mmapIntToStr.count (1000) << endl;return 0;
}
2.3 在 STL map 中查找元素
諸如 map 和 multimap 等關(guān)聯(lián)容器都提供了成員函數(shù) find() ,它讓您能夠根據(jù)給定的鍵查找值。 find() 總是返回一個(gè)迭代器:
multimap <int, string>::const_iterator pairFound = mapIntToStr.find(key);
如果使用的編譯器遵循 C++11 標(biāo)準(zhǔn),可使用關(guān)鍵字 auto 來(lái)簡(jiǎn)化迭代器聲明:
auto pairFound = mapIntToStr.find(key);
編譯器將根據(jù) map::find() 的返回類(lèi)型自動(dòng)推斷出迭代器的類(lèi)型。
應(yīng)首先檢查該迭代器,確保 find() 已成功,再使用它來(lái)訪問(wèn)找到的值:
if (pairFound != mapIntToStr.end())
{cout << "Key " << pairFound->first << " points to Value: ";cout << pairFound->second << endl;
}
elsecout << "Sorry, pair with key " << key << " not in map" << endl;
完整示例代碼如下:
#include <map>
#include <iostream>
#include <string>using namespace std;// 使用迭代器來(lái)訪問(wèn)表示鍵的 first 以及表示值的second
template <typename T>
void DisplayContents (const T& cont)
{for (auto element = cont.cbegin(); element != cont.cend(); ++ element){cout << element->first << " -> " << element->second << endl;}cout << endl;
}int main (){map<string, string> d;d["a"] = "1";d.insert(make_pair("b", "2"));d.insert(make_pair("c", "3"));DisplayContents(d);string key = "c";auto pairFound = d.find(key);if (pairFound != d.end()){cout << "Key " << pairFound->first << " points to Value: ";cout << pairFound->second << endl;}elsecout << "Sorry, pair with key " << key << " not in map" << endl;return 0;
}
2.4 在 STL multimap 中查找元素
如果 2.3 小節(jié)程序使用的是 multimap ,容器可能包含多個(gè)鍵相同的鍵-值對(duì),因此需要找到與指定鍵對(duì)應(yīng)的所有值。為此,可使用 multimap::count() 確定有多少個(gè)值與指定的鍵對(duì)應(yīng),再對(duì)迭代器遞增,以訪問(wèn)這些相鄰的值:
auto pairFound = mmapIntToStr.find(key);
// Check if find() succeeded
if(pairFound != mmapIntToStr.end())
{// Find the number of pairs that have the same supplied keysize_t numPairsInMap = mmapIntToStr.count(1000);for(size_t counter = 0; counter < numPairsInMap; ++ counter ){cout << "Key: " << pairFound->first; // keycout << ", Value [" << counter << "] = ";cout << pairFound->second << endl; // value++ pairFound;}
}
elsecout << "Element not found in the multimap";
2.5 刪除 STL map 或 multimap 中的元素
map 和 multimap 提供了成員函數(shù) erase() ,該函數(shù)刪除容器中的元素。調(diào)用 erase 函數(shù)時(shí)將鍵作為參數(shù),這將刪除包含指定鍵的所有鍵-值對(duì):
mapObject.erase(key);
函數(shù) erase() 的另一種版本接受迭代器作為參數(shù),并刪除迭代器指向的元素:
mapObject.erase(element);
還可使用迭代器指定邊界,從而將指定范圍內(nèi)的所有元素都從 map 或 multimap 中刪除:
mapObject.erase(lowerBound, upperBound);
完整示例代碼:
#include <map>
#include <string>
#include <iostream>using namespace std;template<typename T>
void DisplayContents(const T& cont)
{for (auto element = cont.cbegin(); element != cont.cend(); ++ element)cout<< element->first<< " -> "<< element->second<< endl;cout<< endl;
}int main()
{multimap<int, string> mmapIntToStr;// Insert key-value pairs into the multimapmmapIntToStr.insert(make_pair(3, "Three"));mmapIntToStr.insert(make_pair(45, "Forty Five"));mmapIntToStr.insert(make_pair(-1, "Minus One"));mmapIntToStr.insert(make_pair(1000, "Thousand"));// Insert duplicates into the multimapmmapIntToStr.insert(make_pair(-1, "Minus One"));mmapIntToStr.insert(make_pair(1000, "Thousand"));cout<< "The multimap contains "<< mmapIntToStr.size();cout<< " key-value pairs. "<< "They are: "<< endl;DisplayContents(mmapIntToStr);// Erasing an element with key as -1 from the multimapauto numPairsErased = mmapIntToStr.erase(-1);cout<< "Erased " << numPairsErased << " pairs with -1 as key."<< endl;// Erase an element given an iterator from the multimapauto pair = mmapIntToStr.find(45);if(pair != mmapIntToStr.end()){mmapIntToStr.erase(pair);cout<< "Erased a pair with 45 as key using an iterator"<< endl;}// Erase a range from the multimap...cout << "Erasing the range of pairs with 1000 as key." << endl;mmapIntToStr.erase(mmapIntToStr.lower_bound(1000), mmapIntToStr.upper_bound(1000) );cout<< "The multimap now contains "<< mmapIntToStr.size();cout<< " key-value pair(s)."<< "They are: "<< endl;DisplayContents(mmapIntToStr);
}
總結(jié)
以上是生活随笔為你收集整理的C++ 笔记(24)— STL map 类(map实例化、插入、查找、删除)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 情侣网名微信一男一女
- 下一篇: 2022-2028年中国塑料网格板行业市