将结构数组中的某个条目传递到函数中
Pass in a certain entry within an array of structs into a function
我的结构看起来像:
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]);
}
}
}
相关文章:
- 使用不带参数的函数访问结构元素
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 链表,反向函数,数据结构
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 需要帮助将结构数组传递给函数
- 使用cpp中的结构和函数的多个学生条目
- 如何传递带有通过引用传递的结构参数的函数?
- 在类构造函数中使用结构变量
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在类构造函数中定义结构变量的参数
- 如何在模板类函数中分配结构值?
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 在结构外部调用指向函数的指针
- 函数:结构的数组
- C++错误:只能为对象和函数结构指定存储类
- 将libuv与函数结构一起使用,而不是函数回调
- 从c#调用c++函数-结构体,指针,函数指针
- 函数结构数组输入cin问题