zoukankan      html  css  js  c++  java
  • c++11——改进容器性能

    使用emplace_back就地构造

        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;
    }
    

    使用unordered container无序容器

        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;
    };
    
    +
  • 相关阅读:
    Unity3D研究院之Assetbundle的实战(六十三)
    Unity3D研究院之Assetbundle的原理(六十一)
    常见图片格式详解
    unity 查看打包资源占用
    MUI框架-04-切换页面头部文字重叠
    MUI框架-03-自定义MUI控件样式
    MUI框架-02-注意事项-适用场景-实现页面间传值
    MUI框架-01-介绍-创建项目-简单页面
    安卓app开发-05-Android xml布局详细介绍
    安卓app开发-04- app运行的运行和调试
  • 原文地址:https://www.cnblogs.com/gtarcoder/p/4805733.html
Copyright © 2011-2022 走看看