Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
dangerChihuahua007 Avatar asked Jan 31 '12 21:01

dangerChihuahua007


People also ask

How do you iterate through a set?

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.

What is unordered set in C?

(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.

How does an unordered set work?

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.


2 Answers

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!

like image 150
templatetypedef Avatar answered Sep 30 '22 18:09

templatetypedef


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) {      ... } 
like image 38
Kos Avatar answered Sep 30 '22 17:09

Kos