Storing Class Objects in a List
#include <iostream>
#include <list>
#include <cstring>
using namespace std;
class myclass {
int a, b;
int sum;
public:
myclass() { a = b = 0; }
myclass(int i, int j) {
a = i;
b = j;
sum = a + b;
}
int getsum() { return sum; }
friend bool operator<(const myclass &object1,
const myclass &object2);
friend bool operator>(const myclass &object1,
const myclass &object2);
friend bool operator==(const myclass &object1,
const myclass &object2);
friend bool operator!=(const myclass &object1,
const myclass &object2);
};
bool operator<(const myclass &object1, const myclass &object2)
{
return object1.sum < object2.sum;
}
bool operator>(const myclass &object1, const myclass &object2)
{
return object1.sum > object2.sum;
}
bool operator==(const myclass &object1, const myclass &object2)
{
return object1.sum == object2.sum;
}
bool operator!=(const myclass &object1, const myclass &object2)
{
return object1.sum != object2.sum;
}
int main()
{
int i;
// create first list
list<myclass> listObject1;
for(i=0; i<10; i++) listObject1.push_back(myclass(i, i));
cout << "First list: ";
list<myclass>::iterator p = listObject1.begin();
while(p != listObject1.end()) {
cout << p->getsum() << " ";
p++;
}
cout << endl;
// create a second list
list<myclass> listObject2;
for(i=0; i<10; i++) listObject2.push_back(myclass(i*2, i*3));
cout << "Second list: ";
p = listObject2.begin();
while(p != listObject2.end()) {
cout << p->getsum() << " ";
p++;
}
cout << endl;
// now, merget listObject1 and listObject2
listObject1.merge(listObject2);
// display merged list
cout << "Merged list: ";
p = listObject1.begin();
while(p != listObject1.end()) {
cout << p->getsum() << " ";
p++;
}
return 0;
}
Related examples in the same category