2025年3月16日 星期日 甲辰(龙)年 月十五 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > STL

C++ list(STL list)访问元素的几种方法

时间:03-07来源:作者:点击数:536

不同于之前学过的 STL 容器,访问 list 容器中存储元素的方式很有限,即要么使用 front() 和 back() 成员函数,要么使用 list 容器迭代器。

list 容器不支持随机访问,未提供下标操作符 [] 和 at() 成员函数,也没有提供 data() 成员函数。

通过 front() 和 back() 成员函数,可以分别获得 list 容器中第一个元素和最后一个元素的引用形式。举个例子:

  • #include <iostream>
  • #include <list>
  • using namespace std;
  • int main()
  • {
  • std::list<int> mylist{ 1,2,3,4 };
  • int &first = mylist.front();
  • int &last = mylist.back();
  • cout << first << " " << last << endl;
  • first = 10;
  • last = 20;
  • cout << mylist.front() << " " << mylist.back() << endl;
  • return 0;
  • }

输出结果为:

1 4
10 20

可以看到,通过 front() 和 back() 的返回值,我们不仅能分别获取当前 list 容器中的首尾元素,必要时还能修改它们的值。

除此之外,如果想访问 list 容存储的其他元素,就只能使用 list 容器的迭代器。例如:

  • #include <iostream>
  • #include <list>
  • using namespace std;
  • int main()
  • {
  • const std::list<int> mylist{1,2,3,4,5};
  • auto it = mylist.begin();
  • cout << *it << " ";
  • ++it;
  • while (it!=mylist.end())
  • {
  • cout << *it << " ";
  • ++it;
  • }
  • return 0;
  • }

运行结果为:

1 2 3 4 5

值得一提的是,对于非 const 类型的 list 容器,迭代器不仅可以访问容器中的元素,也可以对指定元素的值进行修改。

当然,对于修改容器指定元素的值,list 模板类提供有专门的成员函数 assign(),感兴趣的读者可自行查找该成员函数的用法。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门