文章目录
(***)1 基础操作
1.1 遍历+正反顺序打印
(1)C++11遍历的方法
for(auto n:l){
// (1)C++11遍历的方法
cout << n << " ";
}
cout << endl;
(2)不支持下标访问
for(int i=0;i<l.size();++i){
// cout << l[i] << " "; // (2)不支持下标访问
}
(3)正序打印
list<int>::iterator it = l.begin(); //(3)正序打印
while(it != l.end()){
cout << *it << " ";
++it;
}
cout << endl;
(4)逆序打印
list<int>::reverse_iterator rit = l.rbegin();//(4)逆序打印
while(rit != l.rend()){
cout << *rit << " ";
++rit;
}
cout << endl;
(完整代码 001_list_Travel.cpp)
#include <iostream>
#include <list>
#include <vector>
using namespace std;
void Travesal(const list<int>& l){
list<int>::const_iterator it = l.cbegin();//cbegin() C++11
while(it != l.cend()){
//cend() C++11
cout << *it << " ";
++it;
}
cout << endl;
}
void TravesalReverse(const list<int>& l){
list<int>::const_reverse_iterator rit = l.crbegin();
while(rit != l.crend()){
cout << *rit << " ";
++rit;
}
cout << endl;
}
int main()
{
list<int> l = {
1,2,3,4,5};// C++11
for(auto n:l){
// (1)C++11遍历的方法
cout << n << " ";
}
cout << endl;
for(int i=0;i<l.size();++i){
// cout << l[i] << " "; // (2)不支持下标访问
}
list<int>::iterator it = l.begin(); //(3)正序打印
while(it != l.end()){
cout << *it << " ";
++it;
}
cout << endl;
list<int>::reverse_iterator rit = l.rbegin();//(4)逆序打印
while(rit != l.rend()){
cout << *rit << " ";
++rit;
}
cout << endl;
Travesal(l);
TravesalReverse(l);
}
1.2 添加,删除
(1)尾添加
l.push_back(6);
(2)尾删除
l.pop_back();
(3) 首添加
l.push_front(-2);
(4) 首删除
l.pop_front();
(源码见002_push_pop.cpp)
#include <iostream>
#include <list>
#include <vector>
using namespace std;
void Travesal(const list<int>& l){
list<int>::const_iterator it = l.cbegin();//cbegin() C++11
while(it != l.cend()){
//cend() C++11
cout << *it << " ";
++it;
}
cout << endl;
}
void TravesalReverse(const list<int>& l){
list<int>::const_reverse_iterator rit = l.crbegin();
while(rit != l.crend()){
cout << *rit << " ";
++rit;
}
cout << endl;
}
int main()
{
list<int> l = {
1,2,3,4,5};// C++11
Travesal(l);
// 尾添加
l.push_back(6);
l.push_back(7);
l.push_back(8);
Travesal(l);
// 尾删除
l.pop_back();
l.pop_back();
l.pop_back();
Travesal(l);
// 首添加
l.push_front(-2);
l.push_front(-1);
l.push_front(0);
Travesal(l);
// 首删除
l.pop_front();
l.pop_front();
l.pop_front();
Travesal(l);
}
1.3 任意位置添加、删除
(1)insert():list的迭代器不能做算术运算,没有算术运算符重载,但是可以自增自减(左闭又开的区间)
// 插入
auto it = l.begin();
++it;
// it = it + 1; // (1)list的迭代器不能做算术运算,没有算术运算符重载,但是可以自增自减
l.insert(it,100); //表示在begin()+1的内存插入100,内存发生改变;此时it指针指向100的后面;(左闭又开的区间)
(2)erase():想要删除100,必须指向100的内存;必须先自减
// 删除
--it;
l