---
title: "forward list源码"
author: "xuning2516"
date: "2013-03-31T21:53:00Z"
tags: []
slug: "forward-list"
draft: false
lastmod: "2013-04-26T00:13:59Z"
id: 1853882
url: "https://xuning2516.iteye.com/blog/1853882"
---

forward\_list 源码学习

```
//forward_list的迭代器是forward_iterator，因此在forward list中需要注意保存前面一个元素的iterator，方便插入和删除。auto posbefore=flist.before_begin();for(auto pos=flist.begin();pos!=flist.end();++pos,++posbefore)

例如在remove_if的成员函数 ，删除的是当前元素的后一个元素。

template <class _Tp, class _Alloc> 
template <class _Predicate>
void slist<_Tp,_Alloc>::remove_if(_Predicate __pred)
{
  _Node_base* __cur = &this->_M_head;
  while (__cur->_M_next) {
    if (__pred(((_Node*) __cur->_M_next)->_M_data))
      this->_M_erase_after(__cur);    //删除的是当前元素的下个元素
    else
      __cur = __cur->_M_next;
  }
}_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;
 }





```