功能描述:

    • 对list容器中数据进行存取

    函数原型:

    • front(); //返回第一个元素
    • back(); //返回最后一个元素

    代码演示:

    1. #include<iostream>
    2. #include<list>
    3. using namespace std;
    4. //list容器的数据存取
    5. //list的迭代器不支持随机访问
    6. void test01() {
    7. //创建list容器
    8. list<int>L1;//默认构造
    9. L1.push_back(10);
    10. L1.push_back(20);
    11. L1.push_back(30);
    12. L1.push_back(40);
    13. cout << "第一个元素为:" << L1.front() << endl;
    14. cout << "最后一个元素为:" << L1.back() << endl;
    15. list<int>::const_iterator it = L1.begin();
    16. it++;//支持双向
    17. it--;
    18. //it = it + 1;//报错, 不支持随机访问
    19. cout << *it<< endl;
    20. }
    21. int main() {
    22. test01();
    23. return 0;
    24. }

    运行结果:
    image.png