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;
}
??正文结束??