Brumbles
Brumbles

Reputation: 5

Sorting an Array of Pointers to Objects

I am trying to sort an Array of pointers to objects by name but i don't know if im going the right way with this. Here is my code so far...

main

Person *personArray[3]; //pointers to person objects

personArray[0] = new Employee("Bill", 1200);
personArray[1] = new Customer("Steve");
personArray[2] = new Employee("Bill", 1200);

Person *tempArray[3];
string temp1;

for(int i=3-1;i>0;i--) 
{
    int min = 0;
    for(int j=1;j<i;j++)
    {
        if(*tempArray[j] < *personArray[min])
        {
            min = j;
        }
    }
  temp1 = tempArray[min]->printname();
  tempArray[min] = tempArray[i];
  tempArray[i] = temp1;
}

class Person
    {
    public:
      Person(string); 
      virtual void printname() = 0;
      bool operator <(const Person& name1) const;
      bool operator ==(const Person& name1) const;

    protected:
      string name;
    };

    bool Person::operator <(const Person& name1) const
    {
       return (this->name < name1.name);
    }
    bool Person::operator ==(const Person& name1) const
    {
       return (this->name == name1.name);
    }

    void Person::printname()
    {
      cout << "Name: " << name << endl;
    }

Upvotes: 0

Views: 944

Answers (1)

rendon
rendon

Reputation: 2363

I think this line is the problem:

if(*tempArray[j] < *personArray[min])

It should be:

if(*personArray[j] < *personArray[min])

Because tempArray hasn't been initialized at this point.

Even more, a temporary object should be sufficient, not an entire array.

And these lines...

temp1 = tempArray[min]->printname();
tempArray[min] = tempArray[i];
tempArray[i] = temp1;

too. tempArray has nothing, it should be something like this:

temp1 = personArray[min]->printname();
personArray[min] = personArray[i];
personArray[i] = temp1;

BTW, temp1 should be the same type of your objects (not string).

Upvotes: 1

Related Questions