品牌区域流量监控看板实战:从实时数据到优化决策支持
2026/10/21 4:54:21
forward_list容器详解forward_list概述forward_list是C++11引入的单向链表容器,相比list更加节省空间,但只支持单向遍历。它是最简单的链表结构,每个元素只包含指向下一个元素的指针。
list节省一个指针的空间size()操作:为节省空间不维护大小信息#include<forward_list>usingnamespacestd;forward_list<int>flst1;// 空forward_listforward_list<string>flst2(10);// 包含10个默认构造的stringforward_list<double>flst3(5,3.14);// 包含5个3.14forward_list<char>flst4={'a','b','c'};// 初始化列表forward_list<int>flst;forward_list<int>flst(10);// 10个默认初始化的int(0)forward_list<int>flst(5,100);// 5个100intarr[]={1,2,3};forward_list<int>flst(arr,arr+3);forward_list<int>flst2(flst1);empty()if(flst.empty()){cout<<"Forward_list is empty";}max_size()cout<<flst.max_size();// 返回forward_list可容纳的最大元素数front()flst.front()=5;// 修改第一个元素intfirst=flst.front();// 访问第一个元素push_front()flst.push_front(5);// 在头部插入5pop_front()flst.pop_front();// 删除头部元素insert_after()autoit=flst.insert_after(flst.before_begin(),15);// 在头部插入15flst.insert_after(it,{1,2,3});// 在指定位置后插入多个元素erase_after()flst.erase_after(flst.before_begin());// 删除第一个元素flst.erase_after(it,flst.end());// 删除从it到end的所有元素clear()flst.clear();// 清空所有元素swap()forward_list<int>flst2;flst.swap(flst2);// 交换两个forward_list的内容splice_after()forward_list<int>flst2={4,5,6};flst.splice_after(flst.before_begin(),flst2);// 将flst2所有元素移动到flst头部remove()flst.remove(5);// 删除所有值为5的元素remove_if()flst.remove_if([](intn){returnn%2==0;});// 删除所有偶数unique()flst.unique();// 删除连续重复元素merge()forward_list<int>flst2={4,5,6};flst.sort();flst2.sort();flst.merge(flst2);// 合并两个已排序forward_listsort()flst.sort();// 升序排序flst.sort(greater<int>());// 降序排序reverse()flst.reverse();// 反转forward_listbefore_begin()autoit=flst.before_begin();// 获取第一个元素前的位置begin()&end()for(autoit=flst.begin();it!=flst.end();++it){cout<<*it<<" ";}#include<iostream>#include<forward_list>#include<algorithm>usingnamespacestd;intmain(){// 创建并初始化forward_listforward_list<int>flst={2,3,4};// 头部操作flst.push_front(1);// 头部插入1// 访问元素cout<<"First element: "<<flst.front()<<endl;// 插入元素autoit=flst.insert_after(flst.begin(),5);// 在第二个位置插入5flst.insert_after(it,{7,8,9});// 在5后面插入7,8,9// 删除元素flst.pop_front();// 删除头部元素flst.remove(8);// 删除所有8// 特殊操作forward_list<int>flst2={10,11,12};flst.splice_after(flst.before_begin(),flst2);// 合并flst2到flstflst.sort();// 排序flst.unique();// 去重// 遍历forward_listcout<<"All elements: ";for(intnum:flst){cout<<num<<" ";}cout<<endl;// 容量信息cout<<"Is empty: "<<(flst.empty()?"Yes":"No")<<endl;return0;}list更节省内存(每个节点少一个指针)