無序容器
傳統 C++ 中的有序容器 std::map/std::set,這些容器內部通過紅黑樹進行實現,插入和搜索的平均複雜度均爲 O(log(size))。在插入元素時候,會根據 < 操作符比較元素大小並判斷元素是否相同,並選擇合適的位置插入到容器中。當對這個容器中的元素進行遍歷時,輸出結果會按照 < 操作符的順序來逐個遍歷。
而無序容器中的元素是不進行排序的,內部通過 Hash 表實現,插入和搜索元素的平均複雜度爲 O(constant),在不關心容器內部元素順序時,能夠獲得顯著的性能提升。
C++11 引入了兩組無序容器:std::unordered_map/std::unordered_multimap 和 std::unordered_set/std::unordered_multiset。
它們的用法和原有的 std::map/std::multimap/std::set/set::multiset 基本類似,這裏比較一下std::map和std::multimap:
#include <iostream>
#include <string>
#include <unordered_map>
#include <map>
int main() {
// 兩組結構按同樣的順序初始化
std::unordered_map<int, std::string> u = {
{1, "1"},
{3, "3"},
{2, "2"}
};
std::map<int, std::string> v = {
{1, "1"},
{3, "3"},
{2, "2"}
};
// 分別對兩種容器進行遍歷
std::cout << "std::unordered_map" << std::endl;
for( const auto & n : u)
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
std::cout << std::endl;
std::cout << "std::map" << std::endl;
for( const auto & n : v)
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
結果:
std::unordered_map
Key:[2] Value:[2]
Key:[1] Value:[1]
Key:[3] Value:[3]
std::map
Key:[1] Value:[1]
Key:[2] Value:[2]
Key:[3] Value:[3]