setクラスのイテレータを使用する

C++ では、イテレータまたはレンジベース for ループを使用してセットを反復処理できます。

  1. Setをイテレータで走査する:
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 使用迭代器遍历Set
std::set<int>::iterator it;
for (it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
  1. Setの範囲を巡回する (C++11以降):
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 使用范围循环遍历Set
for (const int& element : mySet) {
std::cout << element << " ";
}
return 0;
}

どの方法を使ってもSet内の要素を走査できます。

bannerAds