Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
    }
share|improve this question
1  
Are you allowed to use standard library algorithms? If so, use std:sort with a custom predicate. –  juanchopanza Feb 12 at 21:32
    
i dont think so, we were told to look up string::compare and use overloaded operators –  Brumbles Feb 12 at 21:36
add comment

1 Answer

up vote 1 down vote accepted

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

share|improve this answer
    
How could i use a temporary object if there different derived classes? –  Brumbles Feb 12 at 21:49
    
Try with a Person pointer, I think the other objects derive from this. Isn't it? –  rendon Feb 12 at 21:51
    
Yeah but person is an abstract class and can't be instantiated –  Brumbles Feb 12 at 21:58
    
Ok i have it working but its sorting them in reverse alphabetical order –  Brumbles Feb 12 at 22:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.