How does one iterate through an unordered set in C++?
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.
Solution 1:
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:
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:
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;
}