Vector issues with storing class instances

Hello again!

Well, same old school, and same old issues.

I have made a program to get:
name
test scores
average of test scores
highest test score

then output the class average
students below the class average
students with the highest test scores

My instructor wants me to store these into one vector. This is where I get confused. I can get all the information, like name and average etc. I stored these into a vector of my class, meaning I have a vector of class instances (where each student is an instance of my class) Now I just do not know how to output all this data. I am confused as to how output this to find if one element of the vector is greater than another. I am very confused, because I have three things stored in this vector, how will I tell the computer to just look at say, the students highest grade, and compare it to another students?

gah, my brain hurts
vector has several ways of retreiving data. Probably the easiest and most intuitive is to use the [] operator:

1
2
3
score = myvector[0].testscore; // gets first student's score
score = myvector[1].testscore; // gets next
// etc 


Assuming of course 'testscore' is a member of your class representing a student.

You can use myvector.size() to get the number of students in the vector
Ok, so I can use a control structure to output this data. that makes sense. But, lets say I have 3 types of data stored here. I need to output the students with grades that are the highest. I could use max_element for that, that I know. But, how can i access data of a vector of class instances?
You need to either create a function or function object with the function operator overloaded, or overload the < operator for your class to compare the max scores. Say you wanted to pass a function:
1
2
3
4
5
6
bool compareHighests(YourClass a, YourClass b) {
    return a.highest < b.highest;
}
// then when you find the max:
cout << "highest is: " << max_element(yourVector.begin(), yourVector.end(), compareHighests)->highest;
//max_element returns an iterator, so the members of your class will be accessed with -> 
Last edited on
Ok, gotcha. But here is what i am looking for. I have ONE vector, storing ONE instance of class, that has THREE parts. I need to look at one part, how can I do this?
Topic archived. No new replies allowed.