Add object to a list and sort them - C++ STL

C++ examples for STL:list

Description

Add object to a list and sort them

Demo Code

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

using namespace std;

class Employee//from ww w . j  av a2s .  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;
}

Result


Related Tutorials