溫馨提示×

c++ 中的 set 有何遍歷方法

c++
小樊
297
2024-11-29 18:33:55
欄目: 編程語言

在 C++ 中,std::set 是一個關聯容器,它包含一組唯一的元素。遍歷 std::set 的方法有以下幾種:

  1. 使用范圍 for 循環(C++11 及更高版本):
#include <iostream>
#include <set>

int main() {
    std::set<int> my_set = {1, 2, 3, 4, 5};

    for (const auto& element : my_set) {
        std::cout << element << " ";
    }

    return 0;
}
  1. 使用迭代器(C++98 及更高版本):
#include <iostream>
#include <set>

int main() {
    std::set<int> my_set = {1, 2, 3, 4, 5};

    for (std::set<int>::iterator it = my_set.begin(); it != my_set.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}
  1. 使用 C++ 標準庫中的算法(如 std::for_each):
#include <iostream>
#include <set>
#include <algorithm>

int main() {
    std::set<int> my_set = {1, 2, 3, 4, 5};

    std::for_each(my_set.begin(), my_set.end(), [](int element) {
        std::cout << element << " ";
    });

    return 0;
}

以上三種方法都可以用于遍歷 std::set。范圍 for 循環是最簡潔的方法,而迭代器和算法則提供了更多的靈活性和功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女