文章目录
- 前言
- 一、尾插、头插、insert、erase
- 二、reverse、sort
- 总结
前言
C++list的使用:尾插、头插、insert、erase、reverse、sort等的介绍
一、尾插、头插、insert、erase
#include <iostream>
#include <list>
using namespace std;
void test_list1()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);
lt.push_front(10);
lt.push_front(20);
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
// 在第5个位置插入数据
// vector v.insert(v.begin() + 5, val)
list<int>::iterator it = lt.begin();
for (size_t i = 0; i < 5; i++)
{
++it;
}
lt.insert(it, 66);
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
it = find(lt.begin(), lt.end(), 3);
if (it != lt.end())
{
lt.insert(it, 100);
*it *= 2;
// insert 完后it不失效
}
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
it = find(lt.begin(), lt.end(), 2);
if (it != lt.end())
{
lt.erase(it);
//*it *= 2; // 会强制报错
// erase 后it 失效
}
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
// 删除所有的偶数
it = lt.begin();
while (it != lt.end())
{
if (*it % 2 == 0)
{
it = lt.erase(it);
}
else
{
++it;
}
}
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
}
int main()
{
test_list1();
return 0;
}
二、reverse、sort
void test_list02()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);
lt.push_front(10);
lt.push_front(20);
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
reverse(lt.begin(), lt.end());
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
lt.reverse();
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
//sort(lt.begin(), lt.end());
//for (auto e : lt)
//{
// cout << e << " ";
//}
//cout << endl;
lt.sort();
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
}
总结
C++list的使用:尾插、头插、insert、erase、reverse、sort等的介绍