【C++】STL:list

目录

list的基本功能

添加元素 

删除操作 

自建对象使用list


list的基本功能

list是对链表的封装,使得操作起来更加方便。

数组和链表的区别

数组是可以随机访问的,只要我给他具体的索引位置,就能找到这个值。而链表是不能随机访问的,只能按顺序链式访问,所以链表只能使用迭代器iterator。

 

函数名称功能
push_back在尾部添加一个元素
pop_back在尾部删除一个元素
push_front在头部添加一个元素
pop_front在头部删除一个元素
clear清空所有元素
size返回元素的个数
front返回头元素
back返回尾元素
insert在中间插入元素
erase删除中间的元素

添加元素 

#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;

int main()
{
    list<int> lst;

    lst.push_back(1);
    lst.push_front(3);
    lst.push_front(2);

    for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
    {
        int& value = *iter;
        printf("%d\n", value);
    }



    cout << "end" << endl;
    return 0;
}

结果为:

删除操作 

#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;

int main()
{
    list<int> lst;

    lst.push_back(1);
    lst.push_front(3);
    lst.push_front(2);


    for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
    {
        int& value = *iter;
        if(value == 3)
        {
            lst.erase(iter);
            break;
        }
    }

    for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
    {
        int& value = *iter;
        printf("%d\n", value);
    }


    cout << "end" << endl;
    return 0;
}

结果为:

结果中可以看出3被删除了。 

自建对象使用list

#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;

class Object
{
public:
    Object(int id, const char* name)
    {
        this->id = id;
        strcpy(this->name, name);
    }
public:
    int id;
    char name[32];
};

int main()
{
    list<Object> lst;
    lst.push_back(Object(1, "a"));
    lst.push_back(Object(2, "b"));
    lst.push_back(Object(3, "c"));

    /*
    for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
    {
        int& value = *iter;
        printf("%d\n", value);
    }
    */

    for(list<Object>::iterator iter = lst.begin(); iter != lst.end(); iter++)
    {
        Object& value = *iter;
        printf("%d, %s\n", value.id, value.name);
    }

    cout << "end" << endl;
    return 0;
}

结果为:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值