std::set和std::map的插入函數, 通常使用的是這個: pair<iterator, bool> insert(const value_type& x)
set和map往往用二叉平衡樹一類的結構實現, 在最差的情況下(例如, 完全升序或者降序排列), 會導致一直調整"平衡", 導致開銷很大
這時候, 可以使用這個: iterator insert(iterator pos, const value_type& x)即"建議插入", 建議在pos之前插入元素. 如果"建議"正確, 插入耗時將是常數級別的
試驗代碼:
const long MAX = (long)5e6;
int main()
{
set<long> set1, set2, set3, set4;
long i;
int64_t t0 = time(NULL);
for (i=0; i<MAX; i++) {
set1.insert(i);
}
int64_t t1 = time(NULL);
cout << "normal asc insert: " << t1 - t0 << endl;
for (i=0; i<MAX; i++) {
set2.insert(set2.end(), i);
}
int64_t t2 = time(NULL);
cout << "end() insert: " << t2 - t1 << endl;
for (i=MAX; i>0; i--) {
set3.insert(i);
}
int64_t t3 = time(NULL);
cout << "normal desc insert: " << t3 - t2 << endl;
for (i=MAX; i>0; i--) {
set4.insert(set4.begin(), i);
}
int64_t t4 = time(NULL);
cout << "begin() insert: " << t4 - t3 << endl;
return 0;
}
運行結果:
normal asc insert: 8
end() insert: 1
normal desc insert: 8
begin() insert: 1
參考資料:
http://www.velocityreviews.com/forums/t290788-set-insert-with-hint.html