标签:
emplace_back能就地通过参数构造对象,不需要拷贝或者移动内存,相比push_back能更好的避免内存的拷贝和移动,使得容器插入元素的性能得到进一步提升。在大多数情况下应该优先使用emplace_back来代替push_back.
所有的标准库容器(array除外,因为它长度不可改变,不能插入元素)都增加了类似的方法:emplace, emplace_hint, emplace_front, emplace_after, emplace_back.
如果需要使用emplace_xx 来就地构造,则需要提供类或者结构体的构造函数。
struct A{
int a;
int b;
A(int x, int y):a(x), b(y){};
};
int main(){
vector<A> v;
v.emplace_back(1,2); //就地构造,需要结构体或类提供构造函数
cout << v.size() << endl;
return 0;
}
c++11增加了无序容器 unordered_map/unordered_multimap/unordered_set/unordered_multiset,这些容器中的元素不排序,使用哈希进行查找和存储,因此效率更高。
由于无序容器内部使用散列表,因此无序容器的key需要提供hash_value 函数,其他用法和map/set相同,对于自定义的key,需要提供hash函数和比较函数。
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& k1, const Key& k2){
return k1.first == k2.first && k1.second == k2.second;
}
};
int main(){
std::unordered_map<std::string, int> m1;
decltype(m1) m2 = {{"hello", 1}, {"world", 2}};
std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 = {
{{"john", "doe"}, "example"},
{{"mary, "sue"}, "another"}}; //自定义类型的key,需要提供hash函数和比较函数
return 0;
};
标签:
原文地址:http://www.cnblogs.com/gtarcoder/p/4805733.html