C++学习_列表_二

list

C++中的列表是一个双向链表,对插入删除的操作非常快

从最前面插入和从最后面插入

这两个可以实现栈和队列

#include <iostream>
#include <list>

using namespace std;

int main() {
    list<int> a;
    a.push_front(10);
    a.push_front(20);
    a.push_back(30);
    a.push_back(40);
    return 0;
}

访问元素

不同于vector,vector重载了[]操作符,使之可以通过下标访问元素,而list不能,list本身是一个双向链表,只能通过迭代器一个一个去访问

通过find函数访问,通这个函数可以访问到第一个关键词,使用这个函数要引用库

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main() {
    list<int> a = {10, 20, 30, 40};
    auto it = find(a.begin(), a.end(), 30);
    cout << (*it);
    return 0;
}

插入元素

  • 通过push_front()从头插入元素
  • 通过push_back()从尾部插入元素
  • 通过insert()插入任意位置 使用insert()插入之前首先要得得到一个迭代器 ```cpp #include #include #include

using namespace std;

int main() { list a = {10, 20, 30, 40}; auto t = find(a.begin(), a.end(), 30); a.insert(t, 50); auto it = find(a.begin(), a.end(), 50); cout << (*it); return 0; }



## 遍历元素
### 用for循环遍历
```cpp
#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main() {
    list<int> a = {10, 20, 30, 40};
    for(int n : a) {
        cout << n;
    }
    return 0;
}

通过while循环

int main() {
    list<int> a = {10, 20, 30, 40};
    auto it = a.begin();
    while(it != a.end()) {
        cout << (*it) << " ";
        it++;
    }
    return 0;
}

删除元素

  • 通过pop_back()删除最后一个元素
  • 通过pop_front()删除第一个元素
  • 通过erase()删除任意一个元素 同样通过erase()删除之前首先要获得被删除元素的迭代器 ```cpp #include #include #include

using namespace std;

int main() { list a = {10, 20, 30, 40}; a.pop_back(); a.pop_front(); auto t = find(a.begin(), a.end(), 30); a.erase(t); auto it = a.begin(); while(it != a.end()) { cout << (*it) << " "; it++; } return 0; }


## 列表反转
通过reserve()方法来反转
```cpp
#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main() {
    list<int> a = {10, 20, 30, 40};
    a.reverse();
    for(int n : a) {
        cout << n << " ";
    }
    return 0;
}
??正文结束??
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值