gpt4 book ai didi

C++:在链表中查找类的最大值

转载 作者:行者123 更新时间:2023-11-30 03:42:05 25 4
gpt4 key购买 nike

我正在做一项作业,该作业涉及创建申请人的链接列表(存储为一个类(class)),每个申请人都有一个 ID、等级、年份和数值(分数)的值。我需要编写一个函数来搜索此列表中得分最高的申请人并将其返回。我能够找到最高分,但我只会返回那个值,而不是那个特定申请人的整个类(class)。更改我的代码后,我现在得到 4 个值(ID、等级、年份和分数)中每个值的输出,但它们都显示 0,这是初始化值。这是所有相关代码。

#include <iostream>
#include <fstream>
#include <iomanip>
#include "applicant.cpp"

using namespace std;

struct Linkapp
{
Applicant person;
Linkapp *next;
};

class Linkthem
{
protected:
Linkapp *start;
public:
Linkthem(void);
void link(Applicant);
void printthem(void);
Applicant returnbest(void);
};

Applicant best;

Linkthem::Linkthem()
{
start = NULL;
};

void
Linkthem::link(Applicant one)
{
Linkapp *p;
p = new Linkapp;
p->person = one;
p->next = start;
start = p;
}

Applicant Linkthem::returnbest (void)
{
Linkapp *travel;
travel = start;

best = travel->person;

while (travel != NULL)
{
if (travel->person.return_value() > best.return_value())
best = travel->person;
travel = travel->next;
}

return best;
}

int
main()
{
ifstream infile;
Applicant fellow;
Linkthem mylist;
int id, yrs;
char knowledge;

cout.setf(ios::fixed);
cout.precision(2);

infile.open("applicnt.dat");

while ( !infile.eof() )
{
infile >> id >> knowledge >> yrs;
fellow.store_id(id);
fellow.store_skill(knowledge);
fellow.store_years(yrs);
mylist.link(fellow);
}

mylist.printthem();

cout << best.return_id() << ' ' << best.return_skill() << ' ';
cout << best.return_years() << ' ' << best.return_value() << endl;

fellow = mylist.returnbest();

return 0;
}

来自“applicant.cpp”

class Applicant
{
protected:
int id;
char skill;
int years;
float value;
void calc_value(void); // <--- NOT for general use, called by return_value
public:
Applicant(void);
void store_id(int);
void store_skill(char);
void store_years(int);
int return_id(void);
char return_skill(void);
int return_years(void);
float return_value(void);
};

问题肯定出在我的 returnbest 函数中,我只是不确定在哪里。

最佳答案

刚用过 std::max_element std::list (这是双向链接的)或 std::forward_list (这是单链接),但我可能会默认为 std::vector相反:

std::max_element(begin(list), end(list), [](Applicant const& a, Applicant const& b) {
return (a.return_value() < b.return_value());
});

如果比较函数是针对整个Applicant类,定义一个 operator< 可能有意义对于所述类。

关于C++:在链表中查找类的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997937/

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