^(* ̄(oo) ̄)^

  • 首页
  • 博客
  • 文档
  • 网盘
  • 仓库
  • 简介
Keep Learning
  1. 首页
  2. 博客
  3. 正文

c++ 迭代器

2025年1月3日 316点热度

迭代器

iterator头文件中除了为每个容器定义的迭代器外,还包括:

  • 插入迭代器:迭代器被绑定到一个容器上,用于向容器插入元素。
  • 流迭代器:迭代器被绑定到输入或输出流上,用来遍历所关联的IO流。
  • 反向迭代器:迭代器向后移动而不是向前移动。仅forward_list容器没有反向迭代器。
  • 移动迭代器:迭代器不拷贝其中的元素,而是移动他们。

插入迭代器操作:

image-20241209155613743

流迭代器:

image-20241209155805713

image-20241209155953563

反向迭代器:

除forward_list之外,其他容器都支持反向迭代器。递增一个反向迭代器会移动到前一个元素;递减迭代器会移动到下一个元素,颠倒了递增和递减运算符的含义。rbegin()、rend()、crbegin()、crend()、

image-20241209165906726

 std::vector<int> vec = { 0,1,2,3,4,5,6,7,8,9 };
 for (auto r_iter = vec.crbegin(); r_iter != vec.crend(); ++r_iter) 
 {
     std::cout << *r_iter << std::endl; // 9 8 7 6 5 4 3 2 1 0
 }

反向迭代器,会反向处理string,

string line = "first,middle,last";
auto comma = find(line.cbegin(), line.cend(), ','); // const_iterator
std::cout << string(line.cbegin(), comma) << std::endl; // first

auto rcomma = find(line.crbegin(), line.crend(), ','); // const_reverse_iterator
std::cout << string(line.crbegin(), rcomma) << std::endl; // tsal

image-20250102143310649

标签: c++
最后更新:2025年1月3日

九州安所如

程序员

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 zhu

鲁ICP备2026022547号