Store class objects in a list : list « List « C++






Store class objects in a list

Store 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 &o1,const MyClass &o2);
  friend bool operator>(const MyClass &o1,const MyClass &o2);
  friend bool operator==(const MyClass &o1,const MyClass &o2);
  friend bool operator!=(const MyClass &o1,const MyClass &o2);
};

bool operator<(const MyClass &o1, const MyClass &o2)
{
  return o1.sum < o2.sum;
}

bool operator>(const MyClass &o1, const MyClass &o2)
{
  return o1.sum > o2.sum;
}

bool operator==(const MyClass &o1, const MyClass &o2)
{
  return o1.sum == o2.sum;
}

bool operator!=(const MyClass &o1, const MyClass &o2)
{
  return o1.sum != o2.sum;
}

int main()
{
  list<MyClass> lst1;
  for(int i=0; i<10; i++) lst1.push_back(MyClass(i, i));

  cout << "First list: ";
  list<MyClass>::iterator p = lst1.begin();
  while(p != lst1.end()) {
    cout << p->getsum() << " ";
    p++;
  }
  cout << endl;

  // create a second list
  list<MyClass> lst2;
  for(int i=0; i<10; i++) lst2.push_back(MyClass(i*2, i*3));

  cout << "Second list: ";
  p = lst2.begin();
  while(p != lst2.end()) {
    cout << p->getsum() << " ";
    p++;
  }
  cout << endl;

  lst1.merge(lst2);

  cout << "Merged list: ";
  p = lst1.begin();
  while(p != lst1.end()) {
    cout << p->getsum() << " ";
    p++;
  }

  return 0;
}

/* 
First list: 0 2 4 6 8 10 12 14 16 18
Second list: 0 5 10 15 20 25 30 35 40 45
Merged list: 0 0 2 4 5 6 8 10 10 12 14 15 16 18 20 25 30 35 40 45 
*/       
    
  








Related examples in the same category

1.Instantiating an STL List of Integers
2.Use generic list to create a list of chars
3.Use generic list to create list of strings
4.Store class objects with overloaded operators in a list.
5.Use std::copy to print all elements in a list
6.Pass list to a function
7.Uses ostream_iterator and copy algorithm to output list elements
8.Add elements in a multiset to a list
9.access list
10.Comparison Algorithms
11.Add elements in a set to a list
12.Merge two lists.Merge two lists.
13.Using the list as a container for double value