How does one iterate through an unordered set in C++?

C++C++11IterationUnordered Set

C++ Problem Overview


Suppose I have an unordered set

unordered_set<int> my_set;
myset.insert(1);
myset.insert(2);
myset.insert(3);

How do I iterate through it? I don't need to iterate in any order - just as long as I reach each element once. I tried

for (int i = 0; i < my_set.size(); i++)
     cout << my_set[i];

to no avail.

C++ Solutions


Solution 1 - C++

You can use the new range-based for loop:

std::unordered_set<T> mySet;
for (const auto& elem: mySet) {
    /* ... process elem ... */
}

Or, you can use the more traditional iterator-based loop:

std::unordered_set<T> mySet;
for (auto itr = mySet.begin(); itr != mySet.end(); ++itr) {
    /* ... process *itr ... */
}

Or, if you don't have auto support, perhaps because you don't have C++11 support on your compiler:

std::unordered_set<T> mySet;
for (std::unordered_set<T>::iterator itr = mySet.begin(); itr != mySet.end(); ++itr) {
    /* ... process *itr ... */
}

Hope this helps!

Solution 2 - C++

Just like any other collection:

for (auto i = my_set.begin(); i != my_set.end(); ++i) {
    std::cout << (*i) << std::endl;
}

Or a bit more generic way using overloads of begin and end functions (you can write overloads for your own types; they also work on plain arrays):

for (auto i = begin(my_set); i != end(my_set); ++i) { 
    ...
}

Solution 3 - C++

Never used them so far, but I'd guess you can use an iterator the same way you do with std::set:

for(unordered_set<int>::iterator a = my_set.begin(); a != my_set.end(); ++a) {
    int some_int = *a;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondangerChihuahua007View Question on Stackoverflow
Solution 1 - C++templatetypedefView Answer on Stackoverflow
Solution 2 - C++KosView Answer on Stackoverflow
Solution 3 - C++MarioView Answer on Stackoverflow