forward_lsit的erase操作为什么是删除指定的迭代器之后的元素

本文探讨了forward_list容器为何没有erase接口,而使用erase_after,解释了其背后的原因:为保持链表连接性,erase会破坏前后节点,erase_after则通过更新指针避免这一问题。同时提到了可能的解决方案,即在迭代器设计中考虑前驱节点。

问题描述:在forward_list的这个容器中,没有erase接口,只提供了erase_after这个接口。其中erase _after(p)为删除迭代器p指向的位置之后的一个元素。那么为什么不能直接删除当前迭代器指向的元素呢。

首先找到STL中slist.h,可以看到

iterator erase_after(iterator __pos) {
    return iterator((_Node*) this->_M_erase_after(__pos._M_node));
  }

于是转到相应的函数

_Slist_node_base* _M_erase_after(_Slist_node_base* __pos)
  {
    _Slist_node<_Tp>* __next = (_Slist_node<_Tp>*) (__pos->_M_next);
    _Slist_node_base* __next_next = __next->_M_next;
    __pos->_M_next = __next_next;
    destroy(&__next->_M_data);
    _M_put_node(__next);
    return __next_next;
  }

这段代码大概的意思就是

// 伪代码
node* next = cur->next;
node* next_next = next->next;
delete(next);
cur->next = next_next

也就是说,为了保持list的连接,需要知道当前被删除的节点的前驱,如果直接删除当前节点,也就是erase(p),连接性就被破坏了。当然,也可以在设计迭代器时定义一个prev变量保存当前迭代器的前驱(逃)。

`forward_list`是C++ STL的一个单向链表容器。单向链表是一种数据结构,它具有一些优点,如在链表中添加或删除元素更加高效。在使用`forward_list`时,必须使用迭代器来访问元素,而不是像在`vector`或`array`中那样使用下标。以下是`forward_list`的一些基本操作: 1.创建`forward_list`: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f1; // 空的forward_list forward_list<int> f2(3); // 3个元素forward_list,元素默认值为0 forward_list<int> f3(2, 1); // 2个元素forward_list,元素默认值为1 forward_list<int> f4{ 1, 2, 3 }; // 3个元素forward_list,初始化列表为1、2、3 forward_list<int> f5(f4.begin(), f4.end()); // 从迭代器初始化forward_list return 0; } ``` 2.在`forward_list`中插入元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; f.push_front(0); // 在前面插入0 f.insert_after(f.begin(), 4); // 在第一个元素之后插入4 f.insert_after(f.begin(), 2, 5); // 在第一个元素之后插入两个5 f.insert_after(f.begin(), {6, 7, 8}); // 在第一个元素之后插入3个元素 return 0; } ``` 3.在`forward_list`中删除元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; f.pop_front(); // 删除第一个元素 f.erase_after(f.begin()); // 删除第二个元素 f.remove(3); // 删除所有等于3的元素 return 0; } ``` 4.在`forward_list`中查找元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; auto it = find(f.begin(), f.end(), 3); if (it != f.end()) cout << "3 is in the forward_list." << endl; else cout << "3 is not in the forward_list." << endl; return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值