加入收藏 | 设为首页 | 会员中心 | 我要投稿 大连站长网 (https://www.0411zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

C++ list STL list 访问元素的几种办法

发布时间:2022-07-16 06:46:25 所属栏目:语言 来源:互联网
导读:不同于之前学过的 STL 容器,访问 list 容器中存储元素的方式很有限,即要么使用 front() 和 back() 成员函数,要么使用 list 容器迭代器。 list 容器不支持随机访问,未提供下标操作符 [] 和 at() 成员函数,也没有提供 data() 成员函数。 通过 front()
  不同于之前学过的 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(),感兴趣的读者可自行查找该成员函数的用法。

(编辑:大连站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!