Site Overlay

C++ std::list 的简明用法

list 就是链表。

创建 list

list<string> myStrings;

添加元素

myStrings.push_back("back");
myStrings.push_front("front");

遍历

通过 for 循环遍历

for (stringIterator = myStrings.begin();
     stringIterator != myStrings.end();
     stringIterator++)
{
    cout << *stringIterator << endl;
}

运行结果:

front
back

通过 while 循环遍历

list<string>::const_iterator stringIterator;
stringIterator = myStrings.begin();
while(stringIterator != myStrings.end())
{
    cout << *stringIterator << endl;
    stringIterator++;
}
return 0;

如果忘记进行 begin() 赋值,会引发 Segmentation fault

删除元素

myStrings.erase(stringIterator);

在遍历时删除元素

【例子】 删除链表中 5 的倍数。(注意要引用传值,否则不会修改原来的链表)

void filter(list<int> &nums)
{
    list<int>::iterator it;
    it = nums.begin();
    while (it != nums.end())
    {
        if (*it % 5 == 0)
        {
            cout << "erase: " << *it << endl;
            it = nums.erase(it);
        }
        else
        {
            it++;
        }
    }
}

完整程序:

#include <stdio.h>
#include <string>
#include <list>
#include <iostream>

using namespace std;

void filter(list<int> &nums)
{
    list<int>::iterator it;
    it = nums.begin();
    while (it != nums.end())
    {
        if (*it % 5 == 0)
        {
            cout << "erase: " << *it << endl;
            it = nums.erase(it);
        }
        else
        {
            it++;
        }
    }
}

void print(list<int> &nums)
{
    list<int>::iterator it;
    it = nums.begin();
    while (it != nums.end())
    {
        cout << *it << endl;
        it++;
    }
}

int main()
{
    list<int> nums;
    for (int i = 1; i <= 100; i++)
    {
        nums.push_back(i);
    }
    filter(nums);
    print(nums);
}

输出:

erase: 5
erase: 10
erase: 15
erase: 20
erase: 25
erase: 30
erase: 35
erase: 40
erase: 45
erase: 50
erase: 55
erase: 60
erase: 65
erase: 70
erase: 75
erase: 80
erase: 85
erase: 90
erase: 95
erase: 100
1
2
3
4
6
7
8
9
11
12
13
14
16
17
18
19
21
22
23
24
26
27
28
29
31
32
33
34
36
37
38
39
41
42
43
44
46
47
48
49
51
52
53
54
56
57
58
59
61
62
63
64
66
67
68
69
71
72
73
74
76
77
78
79
81
82
83
84
86
87
88
89
91
92
93
94
96
97
98
99

在遍历时增加元素

list<int>::iterator it;
it = nums.begin();
while (it != nums.end())
{
    if (*it % 5 == 0)
    {
        cout << "erase: " << *it << endl;
        nums.insert(it, 666);
    }
    it++;
}

注意事项

const iterator 不可自增

否则将引发:double free or corruption (out)

发表评论

电子邮件地址不会被公开。 必填项已用*标注