Firstly sort the vector by using the name as key .
After that all the same persons will be besides each others.
For Example:
vector<vector<string>>vect {{"James", "70"}, {"Fernando", "40"}, {"Nick", "60"},{"James", "90"},{"Nick", "70"},{"Amit", "50"}};
sort(vect.begin(),vect.end());
for(int i=0;i<vect.size();i++){
cout<<vect[i][0]<<" "<<vect[i][1]<<endl;
}
This will output like following:
Amit 50
Fernando 40
James 70
James 90
Nick 60
Nick 70
After that iterate through the row vector by the following way and calculate the average:
int ma=-1;
string maxPerson="";
int counter=0;
int cumSum=0;
for(int i=0;i<vect.size();i++){
if(i>0&&vect[i][0]!=vect[i-1][0]){
int avg=(cumSum/counter);
if(avg>ma){
ma=avg;
maxPerson=vect[i-1][0];
}
counter=1;
cumSum=stringTonumber(vect[i][1]);
}
else {
counter++;
cumSum+=stringTonumber(vect[i][1]);
}
}
int avg=(cumSum/counter);
if(avg>ma){
ma=avg;
maxPerson=vect[vect.size()-1][0];
}
You can declare ma and avg variable as double to calculate the real average if need. Cz sometimes result can be 90.5 but int will not consider .5.
Whole code:
#include <bits/stdc++.h>
#define LEN 150
using namespace std;
int stringTonumber(string x)
{
int num = 0;
for (int i = 0; i < x.size(); i++) {
num = num * 10 + x[i] - '0';
}
return num;
}
int main()
{
vector<vector<string> > vect{ { "James", "70" }, { "Fernando", "90" }, { "Fernando", "80" }, { "Fernando", "100" }, { "Nick", "60" }, { "James", "80" }, { "Nick", "70" }, { "Amit", "50" } };
sort(vect.begin(), vect.end());
for (int i = 0; i < vect.size(); i++) {
cout << vect[i][0] << " " << vect[i][1] << endl;
}
int ma = -1;
string maxPerson = "";
int counter = 0;
int cumSum = 0;
for (int i = 0; i < vect.size(); i++) {
if (i > 0 && vect[i][0] != vect[i - 1][0]) {
int avg = (cumSum / counter);
if (avg > ma) {
ma = avg;
maxPerson = vect[i - 1][0];
}
counter = 1;
cumSum = stringTonumber(vect[i][1]);
}
else {
counter++;
cumSum += stringTonumber(vect[i][1]);
}
}
int avg = (cumSum / counter);
if (avg > ma) {
ma = avg;
maxPerson = vect[vect.size() - 1][0];
}
cout << maxPerson << " " << ma << endl;
return 0;
}