# 在list开头插入元素
# 在list尾巴插入元素
# 在list中间插入元素
# 删除list中的元素
# 对list中的元素进行反转和排序
Demo1:插入元素
#include <iostream>
#include <list>
using namespace std;
/*list的添加*/
//显示
void display(list<int>list_a, list<int>::iterator it);
int main(int argc, char *argv[])
{
list<int> list_1, list_2;
list<int>::iterator it;
//在前面添加
list_1.push_front(100);
list_1.push_front(100);
list_1.push_front(100);
list_1.push_front(100);
list_1.push_back(11); //在末尾添加
cout << "其他操作前: " << endl;
display(list_1, it);
//在前面插入
it = list_1.begin();
list_1.insert(it, 55);
//在中间插入
++it;
++it;
list_1.insert(it, 56);
//在后面插入
list_1.insert(list_1.end(), 66);
cout << "\n添加之后: " << endl;
display(list_1, it);
//insert(intrator, n, m); 插入n个m
list_1.insert(list_1.begin(), 4, 6);
//将整个list插入
list_2.push_back(8888);
list_2.push_back(8888);
list_2.push_back(8888);
//插入list区间
list_1.insert(it, list_2.begin(), list_2.end());
cout << "\n添加之后: " << endl;
display(list_1, it);
return 0;
}
//显示
void display(list<int>list_a, list<int>::iterator it)
{
cout << "[";
for (it = list_a.begin(); it != list_a.end(); ++it){
cout << *it << " ";
}
cout << "\b]\n";
}
输出:
#include <iostream>
#include <list>
using namespace std;
/*list的删除*/
//显示
void display(list<int>list_a);
int main()
{
list<int> list_a;
list<int>::iterator it;
list_a.push_front(400);
list_a.push_front(300);
//insert返回一个迭代器
it = list_a.insert(list_a.begin(), 222);
list_a.push_front(100);
cout << "删除前:\n";
display(list_a);
//删除
list_a.erase(it);
//list_a.erase(it_1, it_2); //从it_1到it_2,前包后不包
cout << "删除后:\n";
display(list_a);
return 0;
}
//显示
void display(list<int>list_a)
{
list<int>::const_iterator it;
cout << "[";
for (it = list_a.begin(); it != list_a.end(); ++it){
cout << *it << " ";
}
cout << "\b]\n";
}
输出:
#include <iostream>
#include <list>
using namespace std;
/*list反转和排序*/
//显示
void display(list<int>list_a);
int main()
{
list<int> a;
a.push_front(45);
a.push_front(12);
a.push_front(56);
a.push_front(36);
a.push_front(22);
cout << "原list:" << endl;
display(a);
a.sort();
cout << "排序后:" << endl;
display(a);
a.reverse();
cout << "反转后:" << endl;
display(a);
return 0;
}
//显示
void display(list<int>list_a)
{
list<int>::const_iterator it;
cout << "[";
for (it = list_a.begin(); it != list_a.end(); ++it){
cout << *it << " ";
}
cout << "\b]\n";
}
输出: