0

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;
    }
2
  • 1
    Are you allowed to use standard library algorithms? If so, use std:sort with a custom predicate. Commented Feb 12, 2014 at 21:32
  • i dont think so, we were told to look up string::compare and use overloaded operators Commented Feb 12, 2014 at 21:36

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

How could i use a temporary object if there different derived classes?
Try with a Person pointer, I think the other objects derive from this. Isn't it?
Yeah but person is an abstract class and can't be instantiated
Ok i have it working but its sorting them in reverse alphabetical order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.