C++ stl 通用算法和成员函数使用

在stl中既有通用函数,又有相同成员函数主要表现在list中。

以remove为例

    list<int> coll;

    // insert elements from 6 to 1 and 1 to 6
    for (int i=1; i<=6; ++i) {
        coll.push_front(i);
        coll.push_back(i);
    }

    // print all elements of the collection
    cout << "pre:  ";
    copy (coll.cbegin(), coll.cend(),         // source
          ostream_iterator<int>(cout," "));   // destination
    cout << endl;

    // remove all elements with value 3
    remove (coll.begin(), coll.end(),         // range
            3);    
开始是list中的元素为6 5 4 3 2 1 1 2 3 4 5 6

remove之后变成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)。

posted @ 2013-03-31 21:36  xuning2516  阅读(309)  评论(0编辑  收藏  举报