So you have a struct with parameters, like:
struct Student
{
std::string name;
std::array<int, 5> grades;
};
Since this is tagged C++
, I chose to use a std::array<int, 5>
rather than int[5]
.
In my opinion, Student
should not be necessarily inside of Group
, but I guess that's opinion based.
Now you have a Group
which contains students:
struct Group
{
Group(std::vector<Student> students) :
_students{ std::move(students) }
{}
double med(/* ... */) const
{ /* ... */ }
std::vector<Student> _students; // C++ -> use std::vector
};
Say you want to pass the grades of a particular student as parameter of the function med
, than you would simply do:
double Group::med(const std::array<int, 5>& grades) const
{ /* sum up grades, divide by 5, and return the result */ }
And you would call this function as follows:
Student paul{"Paul", {1,2,3,4,5}};
Group group({paul});
group.med(paul.grades);
As suggested in the comments, you might want to pass the name of a student instead of his/her grades:
double med(const std::string& name)
{
// find student
auto it = std::find_if(_students.begin(), _students.end(), [&name](const Student& student)
{
return student.name == name;
});
// if no student by that name
if (it == _students.end())
return -1.0;
// else
int sum{ 0 };
for (const auto& grade : it->grades)
{
sum += grade;
}
return static_cast<double>(sum)/(it->grades.size());
}
Here is a discussion about good C++ books.