需要头文件
指针链接数组
创建
//list 双向链表数组
void text12() {
list<int>lst1;//默认构造函数
list<int>lst2(10);//链表长度为10 空元素
list<int>lst3(lst1);//拷贝构造函数
list<int>lst4(10, 22);
list<int>lst5(lst4.begin(), lst4.end());
list<int>lst6 = lst5;
}
删除、插入、空、迭代器(pop\push\empty\auto\iterator)
void text13() {
list<int>lst = { 1,2,3,4,5 };
lst.push_front(100);//前插入
lst.pop_front();//后删除
lst.push_back(50);//后插入
lst.pop_back();//后删除
cout << lst.size() << endl;//返回元素个数
if (lst.empty()) {
cout << "lst为空" << endl;
}
else {
cout << "lst不为空" << endl;
}
//不用auto
for (list<int>::iterator it = lst.begin(); it != lst.end(); it ++ ) {
cout << *it << " ";
}
cout << endl;
for (auto i = lst.begin(); i != lst.end(); i++) {
cout << *i << " ";
}
cout << endl;
}
插入(insert)
不能+n -n
void text14() {
list<int>lst = { 1,2,3,4,5 };
//指定位置插入元素
lst.insert(lst.begin(), 10);//可以++ -- 不能=2 +2双向
//插入n个相同
lst.insert(lst.begin(), 2, 99);
list<int> lst2(2, 33);
lst.insert(lst.begin(), lst2.begin(), lst2.end());
for (auto i = lst.begin(); i != lst.end(); i++) {
cout << *i << " ";
}
cout << endl;
}
删除(erase)
不能+n -n
void text15() {//删除
list<int>lst = { 1,2,3,4,5 };
lst.erase(lst.begin());//删除第一个·
lst.erase(++lst.begin(), --lst.end());//删除区间 不能+n
for (auto i = lst.begin(); i != lst.end(); i++) {
cout << *i << " ";
}
cout << endl;
//想加n
list<int>lst1 = { 1,2,3,4,5 };
list<int>::iterator it = --lst1.end();
--it;
lst.erase(lst1.begin(), it);
for (auto i = lst1.begin(); i != lst1.end(); i++) {
cout << *i << " ";
}
cout << endl;
}
升序、逆序(sort、reverse)
int cmp(const int& v1, const int& v2) {
return v1 > v2;
}
void text16() {
list<int>lst1 = { 21,92,33,4,45 };
list<int>lst2(lst1);
for (auto i = lst1.begin(); i != lst1.end(); i++) {
cout << *i << " ";
}
cout << endl;
lst1.sort();//升序
for (auto i = lst1.begin(); i != lst1.end(); i++) {
cout << *i << " ";
}
cout << endl;
lst1.reverse();//默认降序
for (auto i = lst1.begin(); i != lst1.end(); i++) {
cout << *i << " ";
}
cout << endl;
lst2.sort(cmp);//倒序
for (auto i = lst2.begin(); i != lst2.end(); i++) {
cout << *i << " ";
}
cout << endl;
}