tags:

views:

61

answers:

3

How do i get access to an element in a set ?

vector<int> myvec (4,100);
int first = myvec.at(0);

set<int> myset;
myset.insert(100);
int setint = ????

Can anybody help ?

+4  A: 
set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
    int setint = *iter;
}
Kristo
You should check `iter!=myset.end()` before dereferencing that iterator.
Space_C0wb0y
if you know you're looking for 100, why not just assign 100 to `setint`?
wilhelmtell
The equivalent to that in the `vector` case is `vecint = *find(myvec.begin(), myvec.end(), 100);`
wilhelmtell
+2  A: 

You can't access set elements by index. You have to access the elements using an iterator.

set<int> myset;
myset.insert(100);
int setint = *myset.begin();

If the element you want is not the first one then advance the iterator to that element. You can look in a set to see if an element exists, using set<>::find(), or you can iterate over the set to see what elements are there.

wilhelmtell
The iterators and positions of elements are invalidated only if you erase items from the set.
UncleBens
Ah, sorry. inserting into a set doesn't invalidate old iterators, and erasing elements doesn't invalidate old iterators either (except of course for iterators pointing at the element removed).
wilhelmtell
+1  A: 

In general I find that this is a good documentation of the STL.

Space_C0wb0y
Thanks .. i will check it out ! :)
mr.bio
http://www.cplusplus.com/reference/ is pretty good too.
Kristo