unordered_map是采用哈希搜索的map。搜索速度上也许要优于map。
需要主意的是,对map对象进行遍历时,该对象有可能是未排序的。
源程序如下:
/* B00011 unordered_map */
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
// Create an unordered_map of three strings (that map to strings)
std::unordered_map<std::string, std::string> u = {
{"RED","#FF0000"},
{"GREEN","#00FF00"},
{"BLUE","#0000FF"}
};
// Iterate and print keys and values of unordered_map
for( const auto& n : u ) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
// Add two new entries to the unordered_map
u["BLACK"] = "#000000";
u["WHITE"] = "#FFFFFF";
// Output values by key
std::cout << "The HEX of color RED is:[" << u["RED"] << "]\n";
std::cout << "The HEX of color BLACK is:[" << u["BLACK"] << "]\n";
return 0;
}
程序运行结果如下:
Key:[BLUE] Value:[#0000FF]
Key:[RED] Value:[#FF0000]
Key:[GREEN] Value:[#00FF00]
The HEX of color RED is:[#FF0000]
The HEX of color BLACK is:[#000000]