C++ Set Traversal: Retrieving Values

In C++, iterators can be used to traverse elements in a set. Here is the specific method:

#include <iostream>
#include <set>

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

    // 使用迭代器遍历set
    for (std::set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}

The code above first creates a set containing integers, then uses an iterator std::set::iterator to iterate over the elements in the set and output the value of each element.

bannerAds