【C++】STL中list容器循环存储结构


前言

提示:list, begin(), end(), 循环链表

本文将探索SGI STL中list容器的循环存储结构,可以在list头文件中确认STL为Silicon Graphics Computer Systems, Inc.(SGI)版本。


提示:以下是本篇文章正文内容,下面案例可供参考

一、list是什么?

list是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的。
链表的组成:链表由一系列结点组成;
结点的组成:一个存储数据元素的数据域,一个存储上一个结点地址的指针域,一个存储下一个结点地址的指针域。
在此SGI STL中的list容器不仅是一个双向链表,还是一个循环链表。由于不同版本的STL对于list的实现不尽相同,所以这里希望读者能明确自己的STL版本,当然对于其他版本的STL也可以自己进行探索。

二、list循环存储结构

1. 代码

代码如下(示例):

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> l;

    l.emplace_back(1);
    l.emplace_back(2);
    l.emplace_back(3);

    list<int>::iterator tail = --l.end();
    list<int>::iterator prev_iter_of_begin = --l.begin();
    list<int>::iterator next_iter_of_end = ++l.end();

	cout << "The previous iterator of begin() is the same as tail: " << (prev(l.begin()) == tail ? "true" : "false") << endl;
    cout << "The next iterator of tail is the same as begin(): " << (next(tail, 1) == l.begin() ? "true" : "false") << endl;
    cout << "The previous iterator of begin() is the same as end(): " << (prev_iter_of_begin == l.end() ? "true" : "false") << endl;
    cout << "the next iterator of end() is the same as begin(): " << (next_iter_of_end == l.begin() ? "true" : "false") << endl;
    
    return 0;
}
The previous iterator of begin() is the same as tail: false
The next iterator of tail is the same as begin(): false
The previous iterator of begin() is the same as end(): true
the next iterator of end() is the same as begin(): true

2. 分析

从上面的代码结果可以看出,list的尾部节点(元素值为3)的下一个节点地址的指针域是指向end(),并非是begin(),而end()节点的下一个节点地址的指针域才是指向begin()。同理,begin()的上一个节点地址指针域是指向end(),并非是尾部节点(元素值为3)。
这个结论可以绘制如下的list双向循环存储结构,这与网络上部分展示的list双向循环存储结构图是不同的!!!
请添加图片描述


总结

文章简单介绍了list的循环存储结构。文章主要是针对SGI STL的版本进行探索,并绘制了list的实际循环存储结构,因为笔者在开发过程中发现网络上的list循环存储结构图给我带来了错误的结论,所以在此介绍了自己的验证结果。
希望您能仔细阅读,因为发现和指正文章中的不足之处,是对我莫大的提升,谢谢!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值