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

本文探讨了STL中list容器的remove函数用法及其实现原理。通过具体示例展示了通用remove算法与list成员函数remove的区别:前者仅替换元素但不真正删除,后者则直接删除指定值的所有实例。此外,还分析了两种方法的时间复杂度及其性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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)。

转载于:https://www.cnblogs.com/xuning2516/archive/2013/03/31/3018749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值