使用范围-based for循环可简洁遍历set,元素自动排序输出为1 3 4 5;2. 迭代器遍历兼容所有c++版本,通过begin()和end()访问元素;3. 反向迭代器实现逆序输出5 4 3 1;4. 结合for_each与Lambda表达式提升代码抽象性。现代C++推荐首选范围-for循环。

在C++中,set 是一种关联容器,用于存储唯一且自动排序的元素。遍历 set 是日常编程中的常见操作。下面介绍几种常用的遍历方法,帮助你高效访问 set 中的每一个元素。
使用范围-based for循环(C++11及以上)
这是最简洁、推荐的方式,适用于现代c++开发。
#include <set> #include <iostream> int main() { std::set<int> numbers = {3, 1, 4, 1, 5}; // 自动去重并排序 for (const auto& value : numbers) { std::cout << value << " "; } return 0; }
输出结果为:1 3 4 5。注意元素已自动排序。
使用迭代器遍历
传统但灵活的方法,适用于所有C++标准版本。
立即学习“C++免费学习笔记(深入)”;
std::set<int> numbers = {3, 1, 4, 1, 5}; for (auto it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; }
通过 begin() 获取起始迭代器,end() 获取末尾之后的位置,用 *it 解引用获取值。
使用反向迭代器(逆序遍历)
如果需要从大到小访问元素,可以使用反向迭代器。
for (auto rit = numbers.rbegin(); rit != numbers.rend(); ++rit) { std::cout << *rit << " "; }
输出结果为:5 4 3 1,即降序输出。
结合算法函数遍历(如for_each)
使用 STL 算法提升代码抽象层次。
#include <algorithm> std::for_each(numbers.begin(), numbers.end(), [](const int& n) { std::cout << n << " "; });
配合 lambda 表达式,可写出更清晰的逻辑处理代码。
基本上就这些常用方式。选择哪种取决于你的编译器支持和编码风格。现代C++优先推荐范围-for循环,简洁安全。


