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;
    }
  • 相关阅读:
    Hadoop出现 Wrong FS: hdfs://......错误的解决方法
    在Linux下安装JDK环境
    卸载Linux自带的JDK
    hadoop1.2.1伪分布模式安装教程
    spring配置bean的生命周期
    spring注入的四种方式
    python re模块search()与match()区别
    VB.NET操作Excel
    位运算
    Python简单源码解析
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/9880428.html
Copyright © 2011-2022 走看看