'how to access only element of unordered_set in c++?
For ex,
unordered_set<int> s ;
s.insert(100);
How do I get value 100 from s?
From http://www.cplusplus.com/reference/unordered_set/unordered_set/begin/,
Notice that an
unordered_set
object makes no guarantees on which specific element is considered its first element. But, in any case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), until invalidated.
So s.begin()
won't always give me value 100?
Please clarify.
Solution 1:[1]
When you have only one element (100), you don't have order issue, so *begin(s)
is 100
.
But, as soon as you have 2 or more elements in unordered_set
, you don't know which value would be the first one (*begin(s)
).
Solution 2:[2]
From the link you gave, you will see that begin() will give you an element.
std::cout << "myset contains:";
for ( auto it = myset.begin(); it != myset.end(); ++it )
std::cout << " " << *it;
std::cout << std::endl;
output: myset contains: Venus Jupiter Neptune Mercury Earth Uranus Saturn Mars
As you can see, using begin() will give you an iterator to the first element of the set, and you can go through all elements.
However, begin(i) will give you the buckets in the same example, and some buckets can be empty, some buckets can contain more than one element.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |