16.7.3【列表list容器的插入和删除】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<iostream>
#include<cstdlib>
using namespace std;
#include <list>
 
 
/*
    3.7.5 list 插入和删除
 
        push_back(elem);//在容器尾部加入一个元素
        pop_back();//删除容器中最后一个元素
        push_front(elem);//在容器开头插入一个元素
        pop_front();//从容器开头移除第一个元素
        insert(pos,elem);//在pos位置插elem元素的拷贝,返回新数据的位置。
        insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。
        insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。
        clear();//移除容器的所有数据
        erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。
        erase(pos);//删除pos位置的数据,返回下一个数据的位置。
        remove(elem);//删除容器中所有与elem值匹配的元素。
*/
 
 
void print_list(const list<int> & L)
{
    for(list<int>::const_iterator cit=L.begin(); cit!=L.end(); cit++)
    {
        cout << *cit << " ";
    }
    cout << endl;
}
 
 
void test375()
{
    list<int> L;
 
    //尾插
    L.push_back(10);
    L.push_back(20);
    L.push_back(30);
    print_list(L);
 
    //头插
    L.push_front(100);
    L.push_front(200);
    L.push_front(300);
    print_list(L);
 
    //尾删
    L.pop_back();
    print_list(L);
 
    //头删
    L.pop_front();
    print_list(L);
 
    //insert插入(需提供迭代器参数)
    L.insert(L.begin(), 999); //在L.begin()位置开头插入999
    print_list(L);
 
    list<int>::iterator it = L.begin();
    L.insert(++it, 666);
    print_list(L);
 
    //erase删除(需提供迭代器参数)
    it = L.begin();
    L.erase(it);
    print_list(L);
 
    //remove移除(根据值)
    L.push_back(55);
    L.push_back(55);
    L.push_back(55);
    print_list(L);
    L.remove(55);
    print_list(L);
 
    //clear清空
    L.clear();
    print_list(L);
}
 
 
int main()
{
    test375();
 
    system("pause");
    return 0;
}

  

 

posted @   yub4by  阅读(78)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示