gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:06:05 25 4
gpt4 key购买 nike

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

主要

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com