Link to home
Start Free TrialLog in
Avatar of Troudeloup
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;
}
SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Troudeloup
Troudeloup

ASKER

yes, i am working on my problem solving ability, especially communications with experts.
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?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>>> 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.