将结构数组中的某个条目传递到函数中

Pass in a certain entry within an array of structs into a function

本文关键字:函数 结构 数组      更新时间:2023-10-16

我的结构看起来像:

struct Student
{
string sStudentFName;
string sStudentLName;
int iTestScore;
char cGrade;
};

然后,我创建了一个名为 Students 的数组,其中包含 20 个 Student 结构

Student Students[20] = {};

然后,我创建了这个函数来打印出每个学生的信息:

void PrintStudentInfo(Student students[], const int iSize)
{
/// Get the longest student name (first and last).
static size_t iLongestFullName = 0;
for (int i = 0; i < iSize; i++)
{
string sFullName = students[i].sStudentFName + ", " + students[i].sStudentLName;
if (iLongestFullName < sFullName.length())
iLongestFullName = sFullName.length();
}
/// Print the scores....
for (int i = 0; i < iSize; i++)
{
string sFullName = students[i].sStudentFName + ", " + students[i].sStudentLName;
cout << left << setfill('.') << setw(16);
cout << sFullName;
cout << students[i].iTestScore;
cout << right << setfill('.') << setw(8);
cout << students[i].cGrade;
cout << endl;
}
}

我想创建一个函数,该函数将打印出每个学生的信息,但前提是它们在iMinScore和iMaxScore之间的某个范围内。

void PrintStudentInfoRange(const int iMinScore, const int iMaxScore, Student students[], const int iSize)
{
for (int i = 0; i < iSize; i++) {
if (students[i].iTestScore >= iMinScore && students[i].iTestScore <= iMaxScore) {
// issue occurs here /
PrintStudentInfo(students[i], iSize);
}
}
}

我通过以下方式调用PrintStudentInfoRange函数:

PrintStudentInfoRange(90, 100, Students, STUDENTS);

此行将打印出每个学生在 90 和 100 之间的信息。

我无法弄清楚将特定条目从学生数组传递到PrintStudentInfo函数的语法。我必须在PrintStudentInfoRange中调用PrintStudentInfo函数我得到的错误是*不存在从"学生"到"学生">的合适转换函数。

提前感谢您的帮助。

PrintStudentInfo需要一个指向Student的指针以及从该指针开始打印的Student数。

因此,您可以做的是将正确的指针传递给第一个学生,然后调整1大小:

PrintStudentInfo(&students[i], 1);

但是,从代码质量的角度来看,我鼓励您编写一个仅打印一个学生的函数,然后由PrintStudentInfo在循环中调用该函数以打印所有学生,并且可以由PrintStudentInfoRange重用。

我还建议根本不使用原始数组,因为它们的行为并不直观。请改用std::vector

你在 PrintStudentInfo(( 和 PrintStudentInfoRange(( 中循环所有学生。像这样派了一个学生进行打印。在下一个级别中,尝试使用 std::vector 代替数组:

void PrintStudentInfo(Student* pstudents)
{
string sFullName = pstudents->sStudentFName + ", " + pstudents->sStudentLName;
cout << left << setfill('.') << setw(16);
cout << sFullName;
cout << pstudents->iTestScore;
cout << right << setfill('.') << setw(8);
cout << pstudents->cGrade;
cout << endl;
}

void PrintStudentInfoRange(const int iMinScore, const int iMaxScore, Student students[], const int iSize)
{
for (int i = 0; i < iSize; i++) {
if (students[i].iTestScore >= iMinScore && students[i].iTestScore <= iMaxScore) {
PrintStudentInfo(&students[i]);
}
}
}