how to access only element of unordered_set in c++?
Asked Answered
S

2

11

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.

Sigmon answered 5/7, 2018 at 9:18 Comment(6)
why do you want to access elements in a set? Sets are usually used to check if a value is there or not.Deeprooted
@Deeprooted Its part of library so I need to access element for some quick hack.Sigmon
You iterate through until you find it, or lookup with unordered_set::findHagood
@Sigmon How are using begin that you get garbage values? I think the problem lies with code you are not showing.Hagood
@Sigmon you should probably create an mcve to show when it's garbage that is returned.Poisoning
Also, see xy problem. You are currently assuming that begin returns garbage instead of showing what you are doing. Please show what you are doing.Poisoning
L
19

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

Laughry answered 5/7, 2018 at 9:27 Comment(0)
D
1

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.

Deeprooted answered 5/7, 2018 at 9:23 Comment(3)
Which bucket first element will be stored ? Will s.begin() fetch first element any bucket where the element is present ? I am newbie to c++.Sigmon
begin() will search all buckets until an element is found. Order is NOT guaranteed. begin(i) will give a way to do this search by yourself.Deeprooted
@Deeprooted I have no idea what you mean with your last paragraph.Hagood

© 2022 - 2024 — McMap. All rights reserved.