不会用list的程序员不是好程序员,C++标准容器list类实例详解
ztj100 2025-01-21 23:12 17 浏览 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 容器类的基本用法,希望对读者有所帮助。
相关推荐
- 使用Python编写Ping监测程序(python 测验)
-
Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...
- 批量ping!有了这个小工具,python再也香不了一点
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...
- python之ping主机(python获取ping结果)
-
#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...
- 网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南
-
太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...
- Vue开发中使用iframe(vue 使用iframe)
-
内容:iframe全屏显示...
- Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)
-
本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...
- Vue基础四——Vue-router配置子路由
-
我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...
- Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)
-
作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...
- swiper在vue中正确的使用方法(vue中如何使用swiper)
-
swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...
- Vue怎么实现权限管理?控制到按钮级别的权限怎么做?
-
在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...
- 【Vue3】保姆级毫无废话的进阶到实战教程 - 01
-
作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...
- Vue3开发极简入门(13):编程式导航路由
-
前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...
- vue路由同页面重定向(vue路由重定向到外部url)
-
在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...
- 那个 Vue 的路由,路由是干什么用的?
-
在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...
- Vue3项目投屏功能开发!(vue投票功能)
-
最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 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)