C++ stl 通用算法和成员函数使用
生活随笔
收集整理的這篇文章主要介紹了
C++ stl 通用算法和成员函数使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在stl中既有通用函數,又有相同成員函數主要表現在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算法具有linear complexity是將容器中的等于value的值得元素使用后續的元素進行替換,這就需要進行deference。因此只是調整元素的位置,而不是真正的刪除。
函數返回的是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的成員函數,他是直接刪除元素。它刪除元素不需要移動元素,只需要進行相應的指針操作。因此具有更好的性能。
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;} }
所以在選擇通用算法和成員函數時,比較具有good performance(具有constant or linear complexity)。
轉載于:https://www.cnblogs.com/xuning2516/archive/2013/03/31/3018749.html
總結
以上是生活随笔為你收集整理的C++ stl 通用算法和成员函数使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创新式开发探索(一) —— 开篇
- 下一篇: 还是service