答案:C++中遍历set常用迭代器和range for循环。使用begin()/end()配合迭代器可正向遍历,元素自动升序且去重;C++11起可用auto简化声明;const_iterator用于只读访问;range for语法更简洁,推荐使用const auto&避免拷贝;反向遍历用rbegin()/rend()实现降序输出。

在C++中,set 是一种关联式容器,内部元素自动按升序排序且不允许重复。遍历 set 容器有多种方式,最常用的是使用迭代器和 C++11 引入的 range for 循环。下面详细介绍这两种方法。
set 提供了 begin() 和 end() 成员函数,分别返回指向第一个元素和末尾后一位的迭代器。通过递增迭代器,可以访问每个元素。
示例如下:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> nums = {5, 2, 8, 2, 1}; // 自动去重并排序
for (set<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
输出结果为:1 2 5 8。注意元素已排序且重复值被去除。
立即学习“C++免费学习笔记(深入)”;
也可以使用 const_iterator 遍历只读集合,或使用 auto 简化声明(C++11 起):
for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
cout << *it << " ";
}
C++11 引入了基于范围的 for 循环(range-based for),语法更简洁直观。
基本格式为:
for (declaration : range) {
// 操作
}
遍历 set 的示例:
for (const auto& num : nums) {
cout << num << " ";
}
这里使用 const auto& 可避免不必要的拷贝,尤其对复杂类型更高效。如果只是读取基本类型(如 int),直接用 auto 也可以。
若需要从大到小访问元素,可使用反向迭代器:
for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
cout << *rit << " ";
}
输出为:8 5 2 1,即降序排列。
基本上就这些。使用 range for 是现代 C++ 推荐的方式,代码更清晰;而传统迭代器在需要手动控制访问位置时仍有用武之地。根据场景选择合适的方法即可。
以上就是C++如何遍历set容器_C++ set迭代器与C++11 range for的使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号