Reputation: 205
I have the following function, which takes a vector of students (who have a name and registration number), it is then calculating the min, max and average mark of those students (their marks are stored in a map), the output is partially correct, it should print each student just once, however the code I have written prints out each student the same number of times as the amount of marks stored in their vectors. I've spent some time trying to fix this, I believe the problem is my third for loop, can someone explain why it's looping like this and how to fix it. Thanks.
string func1(vector<Student>students, float mark) {
int count = 0;
float avg, min, max = 0;
list<string> toPrint;
map<string, float> temp;
vector<float> v;
//for every student
for(size_t a=0; a < students.size(); ++a) {
temp = students[a].getCopyOfMap();
v.erase(v.begin(), v.end());
avg = 0;
min = 0;
max = 0;
count = 0;
for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
stringstream ss;
ss << it->second;
v.push_back(stof(ss.str()));
}
for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
max = *max_element(v.begin(), v.end());
min = *min_element(v.begin(), v.end());
for (size_t b=0; b < v.size(); ++b) {
avg = avg + v[b];
count++;
}
avg = avg/count;
if(avg > mark) {
stringstream out;
out << students[a].getRegNo() << " " << min << " " << max << " " << avg << endl;
toPrint.push_back(out.str());
}
}
}
Upvotes: 0
Views: 50
Reputation: 36
Your 'if' statement should be outside of your third 'for' but still inside of the first 'for'.
Upvotes: 1