C++ list 的使用

list 简介

c++ 中list 是 双向链表容器,不支持随机访问,不过list 的插入和删除动作很快,

list 也是属于RTL标注模板库里面的所以使用的需要先引入#include <list>

list 初始化的方法

#include <iostream>
#include <string>
using namespace std;
#include <list>

int main()
{
    // 创建一个空的list
    list<int> a;
    cout << a.size() << endl;
    // 创建一个10个元素对象
    list<int> b(10);
    // 创建5个元素且5个元素都为明天
    cout << b.size() << endl;
    list<string> c(5, "明天");
    list<string>::iterator it;
    for (it = c.begin(); it != c.end(); it++)
    {
        cout << *it << endl;
    }

    return 0;
}

list方法说明

函数说明
assign(first,last)用迭代器first和last所在元素替换list元素
assign(num,val)用val的num个副本替换list元素
beginlist中第一个元素的引用
backlist中最后一个元素的引用
size返回list的个数
front获取list中第一个元素
end获取list中最后一个元素
empty判断list是否为空,为空返回true
clear清空list元素
pop_back删除list中最后一个元素
pop_front删除list中第一个元素
rbegin返回一个反向迭代器,指向list末尾元素之后
rend返回一个反向迭代器,指向list起始元素
erase(i)删除第i位置的元素(注意不能直接为数组,需要用begin或者end)
erase(start,end)

删除指定的元素返回,注意是前包含后不包含,里面不能是数字

insert(i,x)把 i 插入到x位置
insert(i,x,y)把 i 插入到x到y 的位置
swap与另一个vector交换数据

 demo 练习

#include <iostream>
#include <string>
using namespace std;
#include <list>

int main()
{
      // 声明一个int 类型list
      list<string> list_name;
      // 获取默认list的size
      cout << list_name.size() << endl;
      //在末尾位置添加元素
      list_name.push_back("赵");
      list_name.push_back("钱");
      list_name.push_back("孙");
      list_name.push_back("李");
      // 获取list的size
      cout << list_name.size() << endl;
      // 开始的位置插入元素
      list_name.insert(list_name.begin(), "百家姓:");
      // 结束的位置插入元素
      list_name.insert(list_name.end(), "ok");
      // 删除第一个元素
      list_name.pop_front();
      // 删除最后一个元素
      list_name.pop_back();

      //使用迭代器遍历元素
      list<string>::iterator it;
      for (it = list_name.begin(); it != list_name.end(); it++)
      {
            cout << *it << endl;
      }
      // 获取list第一个元素
      cout << "第一个元素:" << list_name.front() << endl;
      // 获取list最后一个元素
      cout << "最后一个元素:" << list_name.back() << endl;

      // list判空
      if (list_name.empty())
      {
            cout << "list为空" << endl;
      }
      else
      {
            cout << "list不为空" << endl;
      }
      // 清空list
      list_name.clear();
      return 0;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值