当前位置: 首页> 文旅> 文化 > STL-List常用接口

STL-List常用接口

时间:2025/7/14 1:50:27来源:https://blog.csdn.net/2301_77479435/article/details/142059702 浏览次数:0次

List常用接口

insert

list<int>::iterator pos = find(lt.begin(), lt.end(), 3);
if (pos != lt.end())lt.insert(pos, 30);
for (auto e : lt)cout << e << " ";
cout << endl;

list的不会失效,而vector会失效。

erase后均会失效。

解决迭代器失效问题

list<int>::iterator it = lt.begin();
while (it != lt.end())
{if (*it % 2 == 0)it = lt.erase(it);elseit++;
}

核心 erase会返回以删除位置的下一个位置。

清空列表的两种方式

while (it != lt.end())
{lt.erase(it++);
}
lt.clear();

模拟实现list

模拟node节点

template<class T>
struct __list_node
{__list_node<T>* _next;__list_node<T>* _prev;T _data;__list_node(const T& x=T()):_data(x),_next(nullptr),_prev(nullptr){}
};

模拟构造迭代器

template<typename T>
struct __list_iterator
{typedef __list_node<T> Node;Node* _node;__list_iterator(Node* node):_node(node){}//*it;T& operator*(){return _node->_data;}//++it__list_iterator<T> operator++(){_node = _node->_next;return *this;}//it!=end()bool operator!=(__list_iterator<T>& it){return _node != it->_node;}
};

 按照STL原码模拟实现list的结构

template<class T>
class list
{typedef struct __list_node<T> Node;typedef __list_iterator<T> iterator;
public:iterator begin(){return iterator(_head->_next);}iterator end(){return iterator(_head);}//带头双向循环列表list(){_head = new node;_head->_next = _head;_head->_prev = _head;}void push_back(const T& x){Node* tail = _head->_prev;Node* newnode = new Node(x);tail->_next = newnode;newnode->_prev = tail;_head->_prev = newnode;newnode->_next = _head;}
private:Node* _head;
};

iterator begin()
{return iterator(_head->_next);
}
iterator end()
{return iterator(_head);
}

有了迭代器就可以使用范围for 

T* operator->()
{return &_node->_data;
}
struct Date
{int _year = 0;int _mouth = 1;int _day = 1;
};
void test_list()
{list<Date> lt;lt.push_back(Date());lt.push_back(Date());list<Date>::iterator it = lt.begin();while (it != lt.end()){cout << it->_year << it->_mouth << it->_day << endl;++it;}
}

while (it != lt.end())
{//cout << it->_year << it->_mouth << it->_day << endl;cout << (*it)._year << (*it)._mouth << (*it)._day << endl;++it;
}

前后置++ 

//++it
__list_iterator<T>& operator++()
{_node = _node->_next;return *this;
}
__list_iterator<T>& operator++()
{_node = _node->_prev;return *this;
}
//it++	 
__list_iterator<T> operator++(int)
{__list_iterator<T> tmp(*this);_node = _node->_next;return tmp;
}
//it++	 
__list_iterator<T> operator++(int)
{__list_iterator<T> tmp(*this);_node = _node->_next;//(*this)++;return tmp;
}

关键字:STL-List常用接口

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: