With a vector, I can do the following:
vector<int> myvec (4,100);
int first = myvec.at(0);
I have the following set:
set<int> myset;
myset.insert(100);
int setint = ????
How can I access the the element I inserted in the set?
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.
set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
int setint = *iter;
}
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.
You can also use this approach :
set<int>:: iterator it;
for( it = s.begin(); it!=s.end(); ++it){
int ans = *it;
cout << ans << endl;
}
To access a particular index, you can use this :
int first = *next(myset.begin(),0);
int third = *next(myset.begin(),2);
The next function returns set iterator to that position. Usually, this function is not used as its performance is linear. But if the set is small enough and there is a need to access some particular index, one can use this to avoid writing the manual iteration loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With