C++ Builder

La Isla Bonita



Sort Vector by Data Members
Sort Vector by Data Members


Abstract

This article shows how to sort a vector that contains objects of a given type. These objects belong to the Person class, which is defined in the header file SortVectorContainingObjects.h This class also contains the setter and getter inline functions for all data members of the class.

Sorting the vector

The vector can be sorted by any of the data members of the Person class. For example, the vector can be sorted either by Name, or by Age, or by Street Number, or by Street Name, or by Suburb, or by Salary.

For each way of sorting the vector, we need to develop a compare function. For example, to sort the vector by Name we need a function such as:
bool CompareNames(const Person& P1, const Person& P2)
{
  return P1.GetName() < P2.GetName();
}
Then we pass on this function to the SortVector() function as the second argument:
    SortVector( Vector, CompareNames );
The SortVector() function is just a thin wrapper around the sort() function:
    sort(V.begin(), V.end(), pfun);


Form 1 contains a TButton button.

Files

SortVectorContainingObjects.cpp

#include <vcl.h>
#pragma hdrstop

#include "SortVectorContainingObjects.h"
#include <vector>
#include <algorithm>

using std::sort;
using std::vector;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

//Create 5 objects (records) of the Person class
//
Person person1;
Person person2;
Person person3;
Person person4;
Person person5;

// Declare a Vector of Person objects
//
vector Vector;

//Compare functions
//
bool CompareNames(const Person& P1, const Person& P2)
{
  return P1.GetName() < P2.GetName();
}

bool CompareAges(const Person& P1, const Person& P2)
{
  return P1.GetAge() < P2.GetAge();
}

bool CompareStNumbers(const Person& P1, const Person& P2)
{
  return P1.GetStNumber() < P2.GetStNumber();
}

bool CompareStNames(const Person& P1, const Person& P2)
{
  return P1.GetStName() < P2.GetStName();
}

bool CompareSuburbs(const Person& P1, const Person& P2)
{
  return P1.GetSuburb() < P2.GetSuburb();
}

bool CompareSalaries(const Person& P1, const Person& P2)
{
  return P1.GetSalary() > P2.GetSalary();
}

// Sort function
//
void SortVector( vector<Person>& V,
                 bool (pfun)(const Person& P1, const Person& P2 ) )
{
    sort(V.begin(), V.end(), pfun);
}

// Print function
//
void PrintVector( vector<Person> V, String DataMember )
{
    String S;

    for( vector<Person>::size_type i = 0 ; i != Vector.size(); i++)
    {
      if (DataMember == "Name")
          S += String(V[i].GetName()) + "\n";
      else
          if (DataMember == "Age")
              S += String(V[i].GetAge()) + "\n";
          else
              if (DataMember == "StName")
                  S += String(V[i].GetStName()) + "\n";
              else
                  if (DataMember == "StNumber")
                      S += String(V[i].GetStNumber()) + "\n";
                  else
                      if (DataMember == "Suburb")
                          S += String(V[i].GetSuburb()) + "\n";
                      else
                          if (DataMember == "Salary")
                              S += String(V[i].GetSalary()) + "\n";
                          else
                              ShowMessage("Illegal Data Member");
    }

    ShowMessage( S );
}

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    person1.SetName("Maria");
    person1.SetAge(30);
    person1.SetSalary(30000);
    person1.SetStNumber(11);
    person1.SetStName("Jupiter st");
    person1.SetSuburb("Byron Bay");

    person2.SetName("Andrew");
    person2.SetAge(18);
    person2.SetSalary(15000);
    person2.SetStNumber(24);
    person2.SetStName("Mirror st");
    person2.SetSuburb("Red Hill");

    person3.SetName("Alicia");
    person3.SetAge(40);
    person3.SetSalary(35000);
    person3.SetStNumber(105);
    person3.SetStName("Green st");
    person3.SetSuburb("Domain");

    person4.SetName("Paul");
    person4.SetAge(36);
    person4.SetSalary(40000);
    person4.SetStNumber(45);
    person4.SetStName("Winter st");
    person4.SetSuburb("Quake");

    person5.SetName("Rita");
    person5.SetAge(59);
    person5.SetSalary(38000);
    person5.SetStNumber(88);
    person5.SetStName("Cool st");
    person5.SetSuburb("East Gardens");

    Vector.push_back(person1);
    Vector.push_back(person2);
    Vector.push_back(person3);
    Vector.push_back(person4);
    Vector.push_back(person5);

    SortVector( Vector, CompareAges );
    PrintVector( Vector, "Age" );

    SortVector( Vector, CompareNames );
    PrintVector( Vector, "Name" );

    SortVector( Vector, CompareStNumbers );
    PrintVector( Vector, "StNumber" );

    SortVector( Vector, CompareStNames );
    PrintVector( Vector, "StName" );

    SortVector( Vector, CompareSuburbs );
    PrintVector( Vector, "Suburb" );

    SortVector( Vector, CompareSalaries );
    PrintVector( Vector, "Salary" );
}

SortVectorContainingObjects.h

#ifndef SortVectorContainingObjectsH
#define SortVectorContainingObjectsH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <sForms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
        TButton *Button1;
        void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------

//Person Class
//
class Person
{
  private:
    String Name;
    int    Age;
    int    StNumber;
    String StName;
    String Suburb;
    double Salary;

  public:
    void SetName(String name)
    {
        Name = name;
    }
    void SetAge(int age)
    {
        Age = age;
    }
    void SetSalary(double salary)
    {
        Salary = salary;
    }
    void SetStNumber(int st_number)
    {
        StNumber = st_number;
    }
    void SetStName(String st_name)
    {
        StName = st_name;
    }
    void SetSuburb(String suburb)
    {
         Suburb = suburb;
    }

    //-----------------------
    String GetName() const
    {
        return Name;
    }
    int GetAge() const
    {
        return Age;
    }
    double GetSalary() const
    {
        return Salary;
    }
    int GetStNumber() const
    {
        return StNumber;
    }
    String GetStName() const
    {
        return StName;
    }
    String GetSuburb() const
    {
         return Suburb;
    }

};
#endif

Homepage

Copyright © 1997-2003 Rodolfo A. Frino. All rights reserved.