C++stl汎用アルゴリズムとメンバー関数の使用

1488 ワード

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 2 3 5です.
removeの後は6 5 4 2 1 2 4 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)を比較します.