C++11新增无序容器unordered_map/unordered_multimap和unordered_set/unordered_multiset,因为无需排序,比有序容器map/multimap和set/multiset效率高。
map和set底层实现是红黑树,插入元素时会自动排序;unordered_map和unordered_set底层是哈希表,通过哈希来操作元素,效率更高。
因为无序容器底层实现是哈希表,所以对于自定义的key,需要提供Hash函数和比较函数;对于基本类型已实现,无需提供。
unordered_map的基本用法:
#include <unordered_map>
#include <vector>
#include <bitset>
#include <string>
#include <utility>
struct Key {
std::string first;
std::string second;
};
struct KeyHash {
std::size_t operator()(const Key& k) const
{
return std::hash<std::string>()(k.first) ^
(std::hash<std::string>()(k.second) << 1);
}
};
struct KeyEqual {
bool operator()(const Key& lhs, const Key& rhs) const
{
return lhs.first == rhs.first && lhs.second == rhs.second;
}
};
int main()
{
//default constructor: empty map
std::unordered_map<std::string, std::string> m1;
//list constructor
std::unordered_map<int, std::string> m2 =
{
{1, "foo"},
{3, "bar"},
{2, "baz"},
};
//copy constructor
std::unordered_map<int, std::string> m3 = m2;
//move constructor
std::unordered_map<int, std::string> m4 = std::move(m2);
//range constructor
std::vector<std::pair<std::bitset<8>, int>> v = { {0x12, 1}, {0x01, -1} };
std::unordered_map<std::bitset<8>, int> m5(v.begin(), v.end());
//constructor of a custom type
std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 =
{
{ {"John", "Doe"}, "example" },
{ {"Mary", "Sue"}, "another" }
};
return 0;
}