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;
}
原文地址:https://www.cnblogs.com/zhanggaofeng/p/9880428.html