c++ - 对指向对象的指针数组进行排序

标签 c++ arrays sorting object pointers

我正在尝试按名称对指向对象的指针数组进行排序,但我不知道我这样做是否正确。到目前为止,这是我的代码...

主要

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;
    }

最佳答案

我认为这一行是问题所在:

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

应该是:

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

因为此时 tempArray 还没有初始化。

更重要的是,一个临时对象就足够了,而不是整个数组。

还有这些线...

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

也是。 tempArray什么都没有,应该是这样的:

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

顺便说一句,temp1 应该与您的对象类型相同(不是字符串)。

关于c++ - 对指向对象的指针数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740103/

相关文章:

php - 使用array_search,但在找到结果后继续搜索(PHP)

c++ - 在 C++ 中使用合并排序算法合并文件

python - 基于字典键值和字符串编号的列表排序

php - 在 PHP 中对多维数组进行排序?

php - 从 PHP 和 MySQL 中的 2 列创建关联数组

java - 从另一个数组定义数组

c++ - 如果我知道此窗口的句柄,如何将 Ctrl + P 发送到窗口?

c++ - 为什么队列的所有元素都一样,元素在posix线程中加入队列

c++ - Ogre3d/Compositor 相关问题

c++ - 如何创建流对象的集合