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

dangerChihuahua007 picture dangerChihuahua007 · Jan 31, 2012 · Viewed 65.3k times · Source

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.

Answer

templatetypedef picture templatetypedef · Jan 31, 2012

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!