Saturday, February 16, 2008

C++ STL set example

/*
* C++ STL set example
* Anwar Mamat anwar@cse.unl.edu
*/
#include "set"
#include "iostream"
using namespace std;

class Student{
public:
int num;
string name;
};


class Comp
{
public:
bool operator()(Student s1, Student s2)
{
if(s1.num < s2.num )
return true;
else
return false;
}
};

int main(int argc, char* argv[])
{
set <Student, Comp> myStudent;

Student a1;
Student a2;

a1.num = 10;
a1.name = "Anwar";

a2.num = 5;
a2.name = "Ziale";

myStudent.insert(a1);
myStudent.insert(a2);
myStudent.insert(a1);

cout << "The number of students " << myStudent.size() << endl;

set <Student, Comp>::iterator it;
for( it = myStudent.begin(); it != myStudent.end(); it++ ) {
cout << it->num << "\t" << it->name << endl;
}
return 0;
}

4 comments:

Unknown said...

Hello,
Many thanks for your nice example. would you please tell me why you have overloaded the peranthesis here?

BR,
--am.

Unknown said...

return s1.num < s2.num;

instead:

if(s1.num < s2.num )
return true;
else
return false;
}

looks so much better :)

Ben said...

Short concise and easily understandable. Thanks!

Gergely said...

You also need #include "string" at the beginning - otherwise it's perfect. :)