深入理解C++11(十六)

深入理解C++11(十六)

unordered container无序容器
C++11增加了无序容器unordered_map/unordered_multimap和unordered_set/unordered_multiset,由于这些容器中的元素是不排序的,因此,比有序容器map/multimap和set/multiset效率更高。map和set内部是红黑树,在插入元素时会自动排序,而无序容器内部是散列表(Hash Table),通过哈希(Hash),而不是排序来快速操作元素,使得效率更高。由于无序容器内部是散列表,因此无序容器的key需要提供hash_value函数,其他用法和map/set的用法是一样的。不过对于自定义的key,需要提供Hash函数和比较函数。代码清单2-6是无序容器的基本用法:

#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>, double> m5(v.begin(), v.end());
// constructor for a custom type
std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 = {
{ {"John", "Doe"}, "example"},
{ {"Mary", "Sue"}, "another"}
};
}

对于基本类型来说,不需要提供Hash函数和比较函数,用法上和map/set一样,对于自定义的结构体,就稍微复杂一些,需要提供函数和比较函数。

总结:
C++11在性能上做了很大的改进,最大程度减少了内存移动和复制,通过右值引用、forward、emplace和一些无序容器我们可以大幅度改进程序性能。

·右值引用仅仅是通过改变资源的所有者来避免内存的拷贝,能大幅度
提高性能。
·forward能根据参数的实际类型转发给正确的函数。
·emplace系列函数通过直接构造对象的方式避免了内存的拷贝和移动。
·无序容器在插入元素时不排序,提高了插入效率,不过对于自定义key
时需要提供hash函数和比较函数。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值