- 功能:对list容器大小进行操作
- 函数原型
- size(); //返回容器中的元素个数
- empty(); //判断容器是否为空,若为空返回true,非空返回NULL
- resize(num); //重新指定容器的长度为num,若容器变长则以默认值填充新位置;若容器变短,则末尾超出容器长度的元素被删掉
- resize(num, elem); //重新指定容器的长度为num,若容器变长则以elem填充新位置;若容器变短,则末尾超出容器长度的元素被删掉
#include<iostream> #include<list> using namespace std; void printlist(const list<int> &L) { for(list<int>::const_iterator it=L.begin();it!=L.end();it++) cout<<*it<<" "; cout<<endl; } void test1() { //创建list容器 list<int> L1; //添加数据 L1.push_back(1); L1.push_back(2); L1.push_back(3); L1.push_back(4); printlist(L1); //1 2 3 4 if(!L1.empty()) { cout<<"元素个数为: "<<L1.size()<<endl; //4 } else { cout<<"容器为空!"<<endl; } L1.resize(6,8); printlist(L1); //1 2 3 4 8 8 L1.resize(3); printlist(L1); //1 2 3 } int main() { test1(); return 0; }