C++如何遍历set容器_C++ set迭代器与C++11 range for的使用

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

c++如何遍历set容器_c++ set迭代器与c++11 range for的使用

在C++中,set 是一种关联式容器,内部元素自动按升序排序且不允许重复。遍历 set 容器有多种方式,最常用的是使用迭代器和 C++11 引入的 range for 循环。下面详细介绍这两种方法。

使用传统迭代器遍历 set

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。注意元素已排序且重复值被去除。

也可以使用 const_iterator 遍历只读集合,或使用 auto 简化声明(C++11 起):

for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
    cout << *it << " ";
}

使用 C++11 range for 循环遍历

C++11 引入了基于范围的 for 循环(range-based for),语法更简洁直观。

基本格式为:

Friday AI Friday AI

国内团队推出的智能AI写作工具

Friday AI 126 查看详情 Friday AI
for (declaration : range) {
    // 操作
}

遍历 set 的示例:

for (const auto&amp; num : nums) {
    cout << num << " ";
}

这里使用 const auto& 可避免不必要的拷贝,尤其对复杂类型更高效。如果只是读取基本类型(如 int),直接用 auto 也可以。

反向遍历 set

若需要从大到小访问元素,可使用反向迭代器:

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的使用的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。