Store elements with duplicate keys in a multiset. - C++ STL

C++ examples for STL:multiset

Description

Store elements with duplicate keys in a multiset.

Demo Code

#include <iostream>
#include <set>
#include <string>
using namespace std;
class employee {/*  w w  w.  ja va  2 s .c  om*/
  string name;
  string ID;
  string phone;
  string department;
public:
  // Default constructor.
  employee() { ID = name = phone = department = ""; }
  // Construct temporary object using only the department,
  // which is the key.
  employee(string d) {
    department = d;
    name = phone = ID = "";
  }
  // Construct a complete employee object.
  employee(string n, string id, string dept, string p)
  {
    name = n;
    ID = id;
    phone = p;
    department = dept;
  }
  // Accessor functions for employee data.
  string get_name() { return name; }
  string get_id() { return ID; }
  string get_dept() { return department; }
  string get_phone() { return phone; }
};
// Compare objects using department.
bool operator<(employee a, employee b)
{
  return a.get_dept() < b.get_dept();
}
// Create an inserter for employee.
ostream &operator<<(ostream &s, employee &o)
{
  s << o.get_name() << endl;
  s << "Emp#:  " << o.get_id() << endl;
  s << "Dept:  " << o.get_dept() << endl;
  s << "Phone: " << o.get_phone() << endl;
  return s;
}
int main()
{
  multiset<employee> emplist;
  // Initialize the employee list.
  emplist.insert(employee("Tom", "9423",
    "Client Relations", "555-1010"));
  emplist.insert(employee("Susan", "8723",
    "Sales", "555-8899"));
  emplist.insert(employee("Alex", "5719",
    "Repair", "555-0174"));
  emplist.insert(employee("Cary", "0719",
    "Repair", "555-0175"));
  // Declare an iterator to the multiset.
  multiset<employee>::iterator itr = emplist.begin();
  // Display contents of the multiset.
  cout << "Current set: \n\n";
  do {
    //cout << *itr << endl;
    ++itr;
  } while (itr != emplist.end());
  cout << endl;
  // Find all employees in the Repair department.
  cout << "All employees in the Repair department:\n\n";
  employee e("Repair"); // temporary object that contains the Repair key.
  itr = emplist.find(e);
  if (itr != emplist.end()) {
    do {
      //output logic
      ++itr;
    } while (itr != emplist.upper_bound(e));
  }
  // Now find Cary Linus in Repair.
  cout << "Looking for Cary in Repair:\n";
  itr = emplist.find(e);
  if (itr != emplist.end()) {
    do {
      /*if (itr->get_dept() == "Cary") {
        cout << "Found:\n";
        cout << *itr << endl;
        break;
      }
      *///TODO has bug
      ++itr;
    } while (itr != emplist.upper_bound(e));
  }
  return 0;
}

Result


Related Tutorials