简体   繁体   English

对对象的指针数组进行排序

[英]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;
    }

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. 因为tempArray尚未初始化。

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: tempArray没有任何内容,应该是这样的:

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

BTW, temp1 should be the same type of your objects (not string). 顺便说一句, temp1应该与您的对象类型相同(而不是字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM