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.
Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.
(since C++17) Unordered set is an associative container that contains a set of unique objects of type Key. Search, insertion, and removal have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets.
Unordered sets are containers that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value. In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely.
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!
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) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With