C++ stl 通用算法和成员函数使用
在stl中既有通用函數(shù),又有相同成員函數(shù)主要表現(xiàn)在list中。
以remove為例
list<int> coll;// insert elements from 6 to 1 and 1 to 6for (int i=1; i<=6; ++i) {coll.push_front(i);coll.push_back(i);}// print all elements of the collectioncout << "pre: ";copy (coll.cbegin(), coll.cend(), // sourceostream_iterator<int>(cout," ")); // destinationcout << endl;// remove all elements with value 3remove (coll.begin(), coll.end(), // range3); 開始是list中的元素為6 5 4 3 2 1 1 2 3 4 5 6remove之后變成6 5 4 2 1 2 4 5 6 5 6
remove算法具有l(wèi)inear complexity是將容器中的等于value的值得元素使用后續(xù)的元素進行替換,這就需要進行deference。因此只是調(diào)整元素的位置,而不是真正的刪除。
函數(shù)返回的是A forward iterator addressing the new end position of the modified range, one past the final element of the remnant sequence free of the specified value
然而在list中也提供了一個remove的成員函數(shù),他是直接刪除元素。它刪除元素不需要移動元素,只需要進行相應(yīng)的指針操作。因此具有更好的性能。
template <class _Tp, class _Alloc> void list<_Tp, _Alloc>::remove(const _Tp& __value) {iterator __first = begin();iterator __last = end();while (__first != __last) {iterator __next = __first;++__next;if (*__first == __value) erase(__first);__first = __next;} }
所以在選擇通用算法和成員函數(shù)時,比較具有g(shù)ood performance(具有constant or linear complexity)。
轉(zhuǎn)載于:https://www.cnblogs.com/xuning2516/archive/2013/03/31/3018749.html
總結(jié)
以上是生活随笔為你收集整理的C++ stl 通用算法和成员函数使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创新式开发探索(一) —— 开篇
- 下一篇: mvc3分页封装