Vector of Objects
Completed
Write class Student (name, three marks) with average(). Read students into a vector<Student> and print the top student and the class average (1 decimal).
Input
n, then n lines name m1 m2 m3.
Output
Two lines.
Example
Input
3 ann 70 80 90 bob 95 90 100 cy 50 60 70
Output
bob 95.0 78.3
Editor
C++
Hints
emplace_back constructs the object directly inside the vector.
Solution explanation
Keeping a pointer to the best element avoids copying objects while searching.
Show solution
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
Student(string name, int a, int b, int c) : name_(name), total_(a + b + c) {}
const string &name() const { return name_; }
double average() const { return total_ / 3.0; }
private:
string name_;
int total_;
};
int main() {
int n;
cin >> n;
vector<Student> students;
for (int i = 0; i < n; i++) {
string name;
int a, b, c;
cin >> name >> a >> b >> c;
students.emplace_back(name, a, b, c);
}
const Student *top = &students[0];
double sum = 0;
for (const auto &s : students) {
if (s.average() > top->average()) top = &s;
sum += s.average();
}
cout << fixed << setprecision(1);
cout << top->name() << " " << top->average() << "\n" << sum / n << "\n";
return 0;
}