Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an element in a set?

Tags:

c++

set

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?

like image 712
mr.bio Avatar asked Mar 29 '10 20:03

mr.bio


People also ask

How do you access the elements of a 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.


4 Answers

set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
    int setint = *iter;
}
like image 135
Michael Kristofik Avatar answered Oct 18 '22 16:10

Michael Kristofik


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.

like image 33
wilhelmtell Avatar answered Oct 18 '22 18:10

wilhelmtell


You can also use this approach :

 set<int>:: iterator it;
 for( it = s.begin(); it!=s.end(); ++it){
    int ans = *it;
    cout << ans << endl;
 }
like image 21
Rafsan Avatar answered Oct 18 '22 18:10

Rafsan


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.

like image 21
Naresh Bharasagar Avatar answered Oct 18 '22 16:10

Naresh Bharasagar