zoukankan      html  css  js  c++  java
  • Sword STL之map效率问题

    #include <iostream>
    #include <map>
    #include <vector>
    
    using namespace std;
    
    /*
    STL容器类都有一个内置数据类型 value_type 
    value_type本质上就是模板类型
    例如:
    vector<int> v1;
    vector<int>::value_type x;  //定义x变量,x的数据类型就是int
    
    在map关联容器类型中,执行更新操作时,map::operator[]效率更高
    执行新元素插入操作时,map-insert效率更高
    */
    
    template<typename MapType, typename KeyArgType, typename ValueArgtype>
    typename MapType::iterator efficientUpdate(MapType& m, const KeyArgType& k, const ValueArgtype& v)
    {
        typename MapType::iterator it = m.lower_bound(k);
    
        if ((it != m.end()) && !(m.key_comp()(k, it->first)))
        {
            //update
            it->second = v;
            return it;
        }
        else
        {
            //add
            typedef typename MapType::value_type MVT;
            return m.insert(it, MVT(k, v));
        }
    }
    
    
    void test()
    {
        map<int, int> m1;
    
        for (int i = 0; i < 10; i++)
        {
            efficientUpdate<map<int, int>, int, int>(m1, i, i * 2);
        }
    
        map<int, int>::iterator it;
        for (it = m1.begin(); it != m1.end(); ++it)
        {
            cout << it->first << ":" << it->second << endl;
        }
    }
    
    int main()
    {
        test();
        getchar();
        return 0;
    }
  • 相关阅读:
    pixijs设置层级的方法
    6.Linux CPU实时监控mpstat命令详解
    5.Linux vmstat命令详解
    4.Linux iostat命令详解
    3.linux top 命令详解
    2.linux sort 命令详解
    1.Linux vim命令详解
    0.Linux命令参考博客
    洛谷 U140956 新漂亮国大选
    CF457C Elections
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/9880428.html
Copyright © 2011-2022 走看看