温馨提示×

c++遍历set可以使用哪些方法

c++
小樊
83
2024-06-24 16:18:35
栏目: 编程语言

在C++中,可以使用以下方法遍历set

  1. 使用迭代器:
#include <iostream>
#include <set>

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

    for (auto it = mySet.begin(); it != mySet.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}
  1. 使用范围-based for 循环:
#include <iostream>
#include <set>

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

    for (int num : mySet) {
        std::cout << num << " ";
    }

    return 0;
}

这两种方法都可以用来遍历set中的元素。

0