C++ list sort Add object to list and sort

Description

C++ list sort Add object to list and sort

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>

using namespace std;

class Employee// www .  jav a  2s .c o m
{
  public:
    Employee(const char* pszS, int id): sName(pszS), ssID(id) {}
    string sName;
    int ssID;
};

bool operator<(const Employee& s1, const Employee& s2)
{
    return s1.ssID < s2.ssID;
}

void displayEmployees(list<Employee>& employees)
{
    auto iter = employees.begin();
    while(iter != employees.end()){
        Employee& s = *iter;
        cout << s.ssID << " - " << s.sName << endl;
        iter++;
    }
}

int main(int argc, char* pArgs[])
{
    list<Employee> employees;

    employees.push_back(Employee("M", 10));
    employees.push_back(Employee("D", 5));
    employees.push_back(Employee("S", 15));

    cout << "The original list:" << endl;
    displayEmployees(employees);

    employees.sort();
    cout << "\nThe sorted list:" << endl;
    displayEmployees(employees);

    return 0;
}



PreviousNext

Related