【问题标题】:Sorting an Array of Pointers to Objects对指向对象的指针数组进行排序
【发布时间】:2014-03-11 11:55:33
【问题描述】:

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

主要

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

【问题讨论】:

  • 你可以使用标准库算法吗?如果是这样,请将 std:sort 与自定义谓词一起使用。
  • 我不这么认为,我们被告知要查找 string::compare 并使用重载运算符

标签: c++ arrays sorting object pointers


【解决方案1】:

我认为这行是问题所在:

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 应该与您的对象类型相同(不是字符串)。

【讨论】:

  • 如果有不同的派生类,我如何使用临时对象?
  • 尝试使用Person 指针,我认为其他对象源自此。不是吗?
  • 是的,但是 person 是一个抽象类,不能被实例化
  • 好的,我可以正常工作,但它按字母倒序对它们进行排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 2016-07-21
  • 2018-06-07
  • 2011-02-03
  • 1970-01-01
相关资源
最近更新 更多