Troudeloup
asked on
[noob][c++] how do I access set element?
#include <iostream>
#include <set>
using namespace std;
int main()
{
set <int, greater<int> > s;
set <int, greater<int> > ::iterator i;
s.insert ( 4 );
s.insert ( 5 );
cout << "The set contains the elements: " << endl;
for (i=s.begin(); i !=s.end(); i++)
{
cout << *i << endl;
}
i = s.begin();
// can I cout an element of the set?
cout << s.i << endl;
return 0;
}
#include <set>
using namespace std;
int main()
{
set <int, greater<int> > s;
set <int, greater<int> > ::iterator i;
s.insert ( 4 );
s.insert ( 5 );
cout << "The set contains the elements: " << endl;
for (i=s.begin(); i !=s.end(); i++)
{
cout << *i << endl;
}
i = s.begin();
// can I cout an element of the set?
cout << s.i << endl;
return 0;
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
here is an odd thing
s.begin()
cout << i* << endl;
output 5.
i++;
cout << i* << endl;
output 4.
and then
i++ //aka s.end()
cout << i* << endl;
output would be 2.
why is there a 3rd element?
s.begin()
cout << i* << endl;
output 5.
i++;
cout << i* << endl;
output 4.
and then
i++ //aka s.end()
cout << i* << endl;
output would be 2.
why is there a 3rd element?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>>> You shouldn't dereference an iterator that points to s.end() ...Don't output it either.
It is a good chance that it crashes. If the set::end() iterator would have a NULL pointer to indicate the out-of-bounds, dereferencing would crash. You've been lucky that it seems to point to a real node element with an arbitrary data item.
It is a good chance that it crashes. If the set::end() iterator would have a NULL pointer to indicate the out-of-bounds, dereferencing would crash. You've been lucky that it seems to point to a real node element with an arbitrary data item.
ASKER