Hello I am asked to write a program that prints the first three students from a vector of class Student
. I thought of using std::tuple<Student, Student, Student>
. I also should write a member function of class Student::sort
which sorts students by average. Everything works fine but I have a problem: I get the avgs inside the function get_best_three
as wished but in main
I get weird results:
#include <iostream>
#include <vector>
#include <tuple>
class Student {
public:
Student(const std::string&, std::size_t, const std::vector<double>&);
std::string name_;
std::size_t age_;
std::vector<double> marks_;
double avg_;
friend bool sort(const Student&, const Student&);
};
Student::Student(const std::string& name, std::size_t age, const std::vector<double>& marks) :
name_(name), age_(age), marks_(marks) {
}
bool sort(const Student& rhs, const Student& lhs) {
return rhs.avg_ > lhs.avg_;
}
std::tuple<Student, Student, Student> get_best_three(std::vector<Student>& studs) {
for (auto& e : studs) {
double sum = 0;
for (const auto& d : e.marks_)
sum += d;
e.avg_ = sum / e.marks_.size();
std::cout << e.avg_ << std::endl; // ok
}
std::sort(studs.begin(), studs.end(), sort);
return std::make_tuple(*studs.begin(), *(studs.begin() + 1), *(studs.begin() + 2));
}
int main() {
std::vector<Student> vstuds;
vstuds.push_back(Student("Haroun Kdz", 37, std::vector<double>{ 12.97, 7.23, 14.55, 11.00 }));
vstuds.push_back(Student("Hafid Lyd", 39, std::vector<double>{ 7.11, 9.49, 11.67, 8.19 }));
vstuds.push_back(Student( "Ahmed Rhn", 38, std::vector<double>{ 15.57, 14.83, 12.67, 19.57 } ));
vstuds.push_back(Student("Babay lsmr", 40, std::vector<double>{ 12.13, 9.99 , 7.23, 14.63 }));
vstuds.push_back(Student("Zouhir Dj" , 38, std::vector<double>{ 8.72 , 15.67, 11.67, 8.85 }));
vstuds.push_back(Student("Sabri Soc" , 39, std::vector<double>{ 6.99 , 8.12, 1042, 9.45 }));
auto three_best = get_best_three(vstuds);
// wrong results
std::cout << std::get<0>(three_best).name_ << " " << std::get<0>(three_best).avg_ << std::endl;
std::cout << std::get<1>(three_best).name_ << " " << std::get<0>(three_best).avg_ << std::endl;
std::cout << std::get<2>(three_best).name_ << " " << std::get<0>(three_best).avg_ << std::endl;
}
Here is the output:
11.4375 9.115 15.66 10.995 11.2275 266.64 Sabri Soc 266.64 Ahmed Rhn 266.64 Haroun Kdz 266.64
Aucun commentaire:
Enregistrer un commentaire