不会用list的程序员不是好程序员,C++标准容器list类实例详解
ztj100 2025-01-21 23:12 19 浏览 0 评论
C++中的 list(列表)是顺序容器,其中存储的元素并不是内存连续的,这一点和上一节讨论的 deque 是类似的。
list 容器类的特点
稍后几节将要讨论的C++中的 vector(向量)容器中的元素在内存中是连续存储的,这一点恰好和 list 相反。元素相邻存储的好处是随机访问非常方便,可以像类似于C语言数组那样通过下标访问各个元素,但是插入元素开销就比较大了,因为每插入一个元素,都必须移动其他所有元素。
而C++中的 list 则客服了 vector 容器的这个缺点,它允许程序员在 list 的任意位置插入元素,而不会造成很大的开销。不过,就随机访问而言,list 比 vector 慢。
list 的声明与初始化
在C++程序开发中使用 list 容器类是非常方便的,只需要在程序开头包含 <list>头文件就可以了:
#include <list>
list 容器类在 std 命名空间中,因此声明一个 list 容器类对象可以按照下面这种方式:
std::list<objType> obj;
其中 objType 表示数据类型,它可以是任意类型,也可以是一个类,甚至可以是 list 本身,例如:
std::list<int> i; std::list<std::list<int>> li;
我们可以在定义 list 容器类对象时对其初始化(需要c++11支持),例如下面这段C++代码:
std::list<int> mylist = {1, 1, 2, 3, 5};
上面这样的初始化将在 mylist 中填充数据,如前文所述,这些数据元素在内存中的分布不是连续的,倒是有些像链表:
一旦定义好 list 容器类对象并且初始化完毕,我们就可以通过迭代器访问其中的元素了。迭代器可以通过成员函数 begin() 和 end() 辅助使用,下面是一个例子,请看:
#include <iostream> #include <string> #include <list> #include <iterator> using namespace std; int main() { list<int> mylist = {1, 1, 2, 3, 5}; cout<<”List elements are: “; list<int>::iterator it; for(it=mylist.begin();it!=mylist.end();++it) cout<<*it<<” “; }
编译并执行上述C++代码,可以得到如下输出:
List elements are: 1 1 2 3 5
从代码可以看出,迭代器 it 本质上是一个指针,它在 for() 循环中的使用,和常用的整型循环变量在 for() 中的使用非常类似,唯一的区别就是使用 begin() 函数作为起点,end() 函数作为终点。
C++中的 list 容器类也可以倒序遍历,只需将begin()函数和end()函数换成 rbegin() 和 rend() 函数就可以了,这一点和上一节介绍的的 deque 容器类是类似的,不再赘述了。
list 容器类的成员函数
insert() 函数
它可以将给定的元素插入到 list 的指定位置,返回值是一个迭代器,指向最开始插入的元素位置。典型用法如下:
insert(pos, num_elem, elem)
其中 pos 表示将要插入的位置;num_elem 表示要插入的元素数,默认是 1;elem 则表示要插入的元素。下面是一段典型的C++代码实例,请看:
#include <iostream> #include <list> using namespace std; int main() { list<int> mylist = {1,1,2}; list<int>::iterator it = mylist.begin(); // 迭代器指向第 2 个位置 advance(it, 1); // 将元素 3 插入迭代器指向的位置 mylist.insert(it, 3); cout << "The list after inserting 1 element using insert() is : "; for (list<int>::iterator i = mylist.begin();i != mylist.end();i++) cout << *i << " "; cout << endl; return 0; }
代码很简单,我们先指定要插入元素的位置(通过迭代器),然后即可调用 insert() 成员函数将元素 3 插入。编译并执行上述C++代码,可以得到如下输出,请看:
# g++ t1.cpp --std=c++11 # ./a.out The list after inserting 1 element using insert() is : 1 3 1 2
可以看出,这里我们仅将元素 3 插入 1 次,若希望插入多次,则可以通过 insert() 函数的第二个参数指定:
... mylist.insert(it, 2, 3); ...
此时再编译并执行修改后的C++代码,可以得到 1 3 3 1 2 的输出。
push_back() 和 push_front() 函数
list 容器类是一个双向的列表类,因此可以双向插入。push_back() 函数可以将元素插入到 list 容器的尾部,而 push_front() 函数则可以将元素插入到 list 容器的头部。下面这段C++代码是一个简单的实例:
#include <iostream> #include <string> #include <list> #include <iterator> using namespace std; void printlist(list <int> mylist) { list <int> :: iterator it; for(it = mylist.begin(); it != mylist.end(); ++it) cout <<*it<<' '; cout << '\n'; } int main() { std::list<int> mylist = {1, 1, 2, 3}; cout<<"List elements are: "; printlist(mylist); mylist.push_front(0); mylist.push_back(5); cout<<"\nList contents after push_front and push_back: "; printlist(mylist); return 0; }
编译并执行这段C++代码,可以得到如下输出:
# g++ t.cpp --std=c++11 # ./a.out List elements are: 1 1 2 3 List contents after push_front and push_back: 0 1 1 2 3 5
pop_back() 和 pop_front() 函数
这两个函数的功能恰好分别和 push_back() 与 push_front() 函数的功能反过来,pop_back() 函数可以将 list 的尾部元素删除,而 pop_front() 函数则可以将 list 的头部元素删除,显然,在元素头部或者尾部元素被删除后,list 的长度会减少。下面是一段C++代码示例:
#include <iostream> #include <list> #include <iterator> using namespace std; void printlist(list <int> mylist) { list <int> :: iterator it; for(it = mylist.begin(); it != mylist.end(); ++it) cout <<*it<<' '; cout << '\n'; } int main() { std::list<int> mylist = {1, 1, 2, 3, 5}; cout<<"List elements are: "; printlist(mylist); mylist.pop_front(); mylist.pop_back(); cout<<"\nList contents after push_front and push_back: "; printlist(mylist); return 0; }
编译并执行这段C++代码,得到如下输出:
List elements are: 1 1 2 3 5 List contents after push_front and push_back: 1 2 3
size(),empty(),erase(),clear() 函数
list 容器类的 size() 成员函数返回容器内所有元素的个数,empty() 返回容器是否为空,erase() 函数则可以从 list 中删除某个元素,clear() 函数可以删除 list 容器中所有的元素。下面是一段C++代码示例,请看:
#include <iostream> #include <list> #include <iterator> using namespace std; void printlist(list <int> mylist) { list <int> :: iterator it; for(it = mylist.begin(); it != mylist.end(); ++it) cout <<*it<<' '; cout << '\n'; } int main() { std::list<int> mylist = {1, 1, 2, 3, 5}; cout<<"List elements are: "; printlist(mylist); cout<<"size of the list: "<<mylist.size(); list<int>::iterator it = mylist.begin(); if(!(mylist.empty())){ mylist.erase(it); cout<<"\nList after erase first element: "; printlist(mylist); cout<<"New size of the list: "<<mylist.size(); } else cout<<"list is empty"; mylist.clear(); cout<<"\nsize of the list after clear: "<<mylist.size(); return 0; }
编译并执行上述C++代码,得到如下输出,请看:
List elements are: 1 1 2 3 5 size of the list: 5 List after erase first element: 1 2 3 5 New size of the list: 4
front(),back(),swap(),reverse(),sort()函数
其实这些函数的功能能够直接通过它们的名字看出:front() 和 back() 函数分别返回 list 的头部和尾部元素,swap() 和 reverse() 函数则分别可以交换和反转 list,sort() 函数则提供了排序功能。下面是一段C++代码示例:
#include <iostream> #include <list> #include <iterator> using namespace std; void printlist(list <int> mylist) { list <int> :: iterator it; for(it = mylist.begin(); it != mylist.end(); ++it) cout <<*it<<'\t'; cout << '\n'; } int main() { std::list<int> mylist = {1, 1, 2, 3, 5}; cout<<"List elements are: "; printlist(mylist); cout<<"\nFront of the list: "<<mylist.front(); cout<<"\nBack of the list: "<<mylist.back(); cout<<endl; cout<<"\nReversed List: "; mylist.reverse(); printlist(mylist); list<int> oddlist = {1,5,9,3,7}; oddlist.sort(); cout<<"\nContents of odd list:"; printlist(oddlist); mylist.swap(oddlist); cout<<"After swapping\n mylist: "; printlist(mylist); cout<<"Oddlist : "; printlist(oddlist); return 0; }
编译并执行这段C++代码,得到如下输出:
List elements are: 1 1 2 3 5 Front of the list: 1 Back of the list: 5 Reversed List: 5 3 2 1 1 Contents of odd list:1 3 5 7 9 After swapping mylist: 1 3 5 7 9 Oddlist : 5 3 2 1 1
小结
本节主要介绍了C++标准容器类 list 的基本特点,并且结合一些实例说明了 list 容器类的基本用法,希望对读者有所帮助。
相关推荐
- 其实TensorFlow真的很水无非就这30篇熬夜练
-
好的!以下是TensorFlow需要掌握的核心内容,用列表形式呈现,简洁清晰(含表情符号,<300字):1.基础概念与环境TensorFlow架构(计算图、会话->EagerE...
- 交叉验证和超参数调整:如何优化你的机器学习模型
-
准确预测Fitbit的睡眠得分在本文的前两部分中,我获取了Fitbit的睡眠数据并对其进行预处理,将这些数据分为训练集、验证集和测试集,除此之外,我还训练了三种不同的机器学习模型并比较了它们的性能。在...
- 机器学习交叉验证全指南:原理、类型与实战技巧
-
机器学习模型常常需要大量数据,但它们如何与实时新数据协同工作也同样关键。交叉验证是一种通过将数据集分成若干部分、在部分数据上训练模型、在其余数据上测试模型的方法,用来检验模型的表现。这有助于发现过拟合...
- 深度学习中的类别激活热图可视化
-
作者:ValentinaAlto编译:ronghuaiyang导读使用Keras实现图像分类中的激活热图的可视化,帮助更有针对性...
- 超强,必会的机器学习评估指标
-
大侠幸会,在下全网同名[算法金]0基础转AI上岸,多个算法赛Top[日更万日,让更多人享受智能乐趣]构建机器学习模型的关键步骤是检查其性能,这是通过使用验证指标来完成的。选择正确的验证指...
- 机器学习入门教程-第六课:监督学习与非监督学习
-
1.回顾与引入上节课我们谈到了机器学习的一些实战技巧,比如如何处理数据、选择模型以及调整参数。今天,我们将更深入地探讨机器学习的两大类:监督学习和非监督学习。2.监督学习监督学习就像是有老师的教学...
- Python 模型部署不用愁!容器化实战,5 分钟搞定环境配置
-
你是不是也遇到过这种糟心事:花了好几天训练出的Python模型,在自己电脑上跑得顺顺当当,一放到服务器就各种报错。要么是Python版本不对,要么是依赖库冲突,折腾半天还是用不了。别再喊“我...
- 神经网络与传统统计方法的简单对比
-
传统的统计方法如...
- 自回归滞后模型进行多变量时间序列预测
-
下图显示了关于不同类型葡萄酒销量的月度多元时间序列。每种葡萄酒类型都是时间序列中的一个变量。假设要预测其中一个变量。比如,sparklingwine。如何建立一个模型来进行预测呢?一种常见的方...
- 苹果AI策略:慢哲学——科技行业的“长期主义”试金石
-
苹果AI策略的深度原创分析,结合技术伦理、商业逻辑与行业博弈,揭示其“慢哲学”背后的战略智慧:一、反常之举:AI狂潮中的“逆行者”当科技巨头深陷AI军备竞赛,苹果的克制显得格格不入:功能延期:App...
- 时间序列预测全攻略,6大模型代码实操
-
如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享,欢迎移步宝藏公众号...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)