Access an element in a set?

You can also use this approach :

 set<int>:: iterator it;
 for( it = s.begin(); it!=s.end(); ++it){
    int ans = *it;
    cout << ans << endl;
 }

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.


set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
    int setint = *iter;
}

Tags:

C++

Set