功能描述:

  • 对list容器的大小进行操作。

函数原型:

  • size(); //返回容器中元素的个数
  • empty(); //判断容器是否为空
  • resize(num); //重新指定容器长度为num,若容器变长,则默认值填充新的位置。

    1. //若容器变短,则末尾超出容器长度的元素被删除。
  • resize(num,elem); //重新指定容器长度为num,若容器变长,则以elem填充新的位置。

    1. //若容器变短,则末尾超出容器长度的元素被删除。<br />代码演示:

    ```cpp

    include

    include

    using namespace std; //list容器大小操作 void printList(const list& L) { for (list::const_iterator it = L.begin(); it != L.end(); it++) {

    1. cout << *it << " ";

    } cout << endl; }

//赋值 void test01() { //创建list容器 listL1;//默认构造

  1. //添加数据
  2. L1.push_back(10);
  3. L1.push_back(20);
  4. L1.push_back(30);
  5. L1.push_back(40);
  6. //遍历容器
  7. printList(L1);
  8. //判断容器是否为空
  9. if (L1.empty()) {
  10. cout << "容器为空!" << endl;
  11. }
  12. else {
  13. cout << "容器不为空!" << endl;
  14. cout << "L1中的元素个数为:" << L1.size() << endl;
  15. }
  16. //重新指定大小
  17. L1.resize(7);//扩容,默认值填充
  18. printList(L1);
  19. L1.resize(10,100);//扩容,指定值填充
  20. printList(L1);
  21. L1.resize(2);//缩小
  22. printList(L1);

}

int main() { test01(); return 0; } ``` 运行结果:
image.png