mr.bio
mr.bio

Reputation: 1686

Access an element in a 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?

Upvotes: 22

Views: 120373

Answers (5)

ferdymercury
ferdymercury

Reputation: 828

If performance is not important, one can also make a temporary copy to vector in order to access a specific element with a lazy one-liner.

int setint = vector<int>(myset.begin(), myset.end()).at(0);

Replace .at(0) with any index (you are sure of), or with .back() to get the last element.

Upvotes: 0

Naresh Bharasagar
Naresh Bharasagar

Reputation: 81

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.

Upvotes: 8

Rafsan
Rafsan

Reputation: 151

You can also use this approach :

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

Upvotes: 6

wilhelmtell
wilhelmtell

Reputation: 58725

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.

Upvotes: 17

Michael Kristofik
Michael Kristofik

Reputation: 35218

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

Upvotes: 17

Related Questions