#include <vector>
#include <string>
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
bool fun(int a)
{
return a>5;
}
int main()
{
// 构造
list<int> l1 = {1,2,3,4,5};
list<int> l2 {1,2,3,4,5};
list<int> l3 (10,2);
list<int> l4 (10);
list<int> l5 (l1.begin()++,l1.end()--); //不能+或-固定值 !!!!! 因为链表无法所以索引
// 空间 对比vector 因为是链式的,动态分配空间,不存在 已分配空间(capacity)这个熟悉
l1.size();
//l1.capacity();
l1.empty();
l1.max_size();
// l1.reserve();
cout << "resize前:" << endl;
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ",";
cout << endl;
l1.resize(10); //自动用0填充
cout << "resize后:" << endl;
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ",";
cout << endl;
// iterator begin,end * reverse const cr 8个迭代器
list<int>::const_iterator it1 = l1.cbegin();
list<int>::reverse_iterator it2 = l1.rbegin();
list<int>::const_reverse_iterator it3 = l1.crbegin();
// 常规操作
l1.push_back(222);
l1.push_front(333);
l1.pop_back();
l1.pop_front();
l1.emplace_back(222);
l1.emplace_front(333);
l1.pop_back();
l1.pop_front();
cout << "++++++++++++++++++++++++++\n";
// 取值 没有at()
l1.front();
l1.back();
// 删除
l1.erase(l1.begin());
l1.clear();
// 赋值
l1.assign(4, 0);
l1.assign(++l2.begin(), ++l2.end());
l1.swap(l2);
cout << "++++++++++++++++++++++++++\n";
// insert 可用emplace替换
l2 = {222,333,444,555};
l1.insert(l1.begin(), 5); //插入元素 5;
l1.insert(l1.begin(), l2.begin()++, l2.end()--); //前插 [)
// 以下list 有 vector没有
l1 = {3,4,7,8,3,4,0,5,3,6};
l1.sort();
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ",";
cout << endl;
cout << "merge: 合并" << endl;
l2 = {33,44,55,66};
l1.merge(l2); //将l2合并到l1中 若l1,l2都有序, 合并后还是有序
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ",";
cout << endl;
l1.remove(3); //按值删除
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ",";
cout << endl;
l1 = {1,2,3,3,3,3,4,5,3,9};
l1.unique();
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ ) //1,2,3,4,5,3,9, 只能去连续的重复元素
cout << *tmp << ",";
cout << endl;
// 插入 功能同vector中insert()
l1.splice(l1.begin(), l2, l2.begin(), l2.end());
l1.splice(l1.begin(), l2);
l1 = {1,2,3,4,5,6,7,8};
l2 = {11,22,33,44};
l1.splice(l1.begin(), l2, --l2.end()); //插入l2序列中 --l2.end()指向的元素(1个)
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ","; // 44,1,2,3,4,5,6,7,8,
cout << endl;
l1 = {1,2,3,4,5,6,7,8};
l1.remove_if(fun);
for(auto tmp=l1.begin(); tmp!=l1.end(); tmp++ )
cout << *tmp << ","; // 1,2,3,4,5,
cout << endl;
return 0;
}
c++ STL list构造及常用方法
最新推荐文章于 2023-07-19 22:33:53 发布