地圖型別
常規地圖
對映是一個關聯容器,包含鍵值對。
#include <string>
#include <map>
std::map<std::string, size_t> fruits_count;
在上面的例子中,std::string
是鍵型別,size_t
是一個值。
該鍵充當地圖中的索引。每個金鑰必須是唯一的,必須訂購。
-
如果你需要具有相同鍵的多個元素,請考慮使用
multimap
(如下所述) -
如果你的值型別未指定任何排序,或者你想覆蓋預設排序,則可以提供一個:
#include <string> #include <map> #include <cstring> struct StrLess { bool operator()(const std::string& a, const std::string& b) { return strncmp(a.c_str(), b.c_str(), 8)<0; //compare only up to 8 first characters } } std::map<std::string, size_t, StrLess> fruits_count2;
如果
StrLess
比較器為兩個鍵返回false
,即使它們的實際內容不同,它們也被認為是相同的。
多圖
Multimap 允許具有相同鍵的多個鍵值對儲存在地圖中。否則,它的介面和建立非常類似於常規地圖。
#include <string>
#include <map>
std::multimap<std::string, size_t> fruits_count;
std::multimap<std::string, size_t, StrLess> fruits_count2;
雜湊地圖(無序地圖)
雜湊對映儲存類似於常規對映的鍵值對。雖然它沒有按鍵來排序元素。相反,金鑰的雜湊值用於快速訪問所需的鍵值對。
#include <string>
#include <unordered_map>
std::unordered_map<std::string, size_t> fruits_count;
無序地圖通常更快,但元素不會以任何可預測的順序儲存。例如,迭代 unordered_map
中的所有元素會以看似隨機的順序給出元素。