Sword STL之map效率问题
生活随笔
收集整理的這篇文章主要介紹了
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))){//updateit->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;
}
?
總結
以上是生活随笔為你收集整理的Sword STL之map效率问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: easyui---修改删除查询
- 下一篇: WebBIOS使用手册