如何遍历C++ STL容器?

要遍历 stl 容器,可以使用容器的 begin() 和 end() 函数获取迭代器范围:向量:使用 for 循环遍历迭代器范围。链表:使用 next() 成员函数遍历链表元素。映射:获取键值对迭代器,使用 for 循环遍历。

如何遍历C++ STL容器?

如何遍历 C++ STL 容器

遍历 C++ 标准模版库 (STL) 容器是程序员日常工作中必不可少的一项任务。STL 提供了一系列预定义数据结构,如向量、链表和映射,每个结构都有自己的遍历方法。

遍历 STL 矢量

要遍历一个矢量,我们可以使用 begin()end() 函数获得迭代器范围:

立即学习“C++免费学习笔记(深入)”;

#include int main() {  std::vector v = {1, 2, 3, 4, 5};  // 使用基于范围的 for 循环  for (int num : v) {    std::cout << num << " ";  }  std::cout << std::endl;  // 使用迭代器  for (std::vector::iterator it = v.begin(); it != v.end(); ++it) {    std::cout << *it << " ";  }  std::cout << std::endl;  return 0;}

输出:

1 2 3 4 5 1 2 3 4 5 

遍历 STL 链表

要遍历一个链表,我们可以使用链表的 front()back() 函数以及该链表的 next() 成员函数:

#include int main() {  std::list l = {1, 2, 3, 4, 5};  // 使用基于范围的 for 循环  for (int num : l) {    std::cout << num << " ";  }  std::cout << std::endl;  // 使用迭代器  std::list::iterator it = l.begin();  while (it != l.end()) {    std::cout << *it <next();  }  std::cout << std::endl;  return 0;}

输出:

1 2 3 4 5 1 2 3 4 5 

遍历 STL 映射

要遍历一个映射,我们可以使用映射的 begin()end() 函数获取键值对的迭代器:

#include int main() {  std::map m = {{"Apple", 1}, {"Banana", 2}, {"Cherry", 3}};  // 使用基于范围的 for 循环  for (auto const& [key, value] : m) {    std::cout << key << ": " << value << std::endl;  }  std::cout << std::endl;  // 使用迭代器  for (std::map::iterator it = m.begin(); it != m.end(); ++it) {    std::cout <first << ": " <second << std::endl;  }  return 0;}

输出:

Apple: 1Banana: 2Cherry: 3Apple: 1Banana: 2Cherry: 3

以上就是如何遍历C++ STL容器?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1453205.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月18日 05:46:19
下一篇 2025年12月18日 05:46:32

相关推荐

发表回复

登录后才能评论
关注微信