throwthedays
throwthedays

Reputation: 159

How to compare a variable to member variables of objects contained in a vector

I have a vector std::vector<StudentGradeInfo> gradebook; objects of the class StudentGradeInfo. The StudentGradeInfo class contains the following member variables: std::string studentName; int studentID; std::string major;

What I need to do is overload the == operator to compare the ID input from the user and compare it to the studentID member variables of the objects in the vector std::vector<StudentGradeInfo> gradebook;.

How would I go about looping through the vector to compare the ID's? It would probably be a non-member function since it is comparing an int variable to a member function of an object, but I do not know how to do this.

Upvotes: 0

Views: 334

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

I suppose you want to loop through the vector to find a studentGrandeInfo-object with a particular ID. You can accomplish this rather easy by using std::find_if together with a lambda-function for the proper comparison. The code could look as follows:

int toFind = 4219; // some ID
auto it = std::find_if(
gradebook.begin(), gradebook.end(),
[&toFind](const StudentGradeInfo& x) { return x.studentID == toFind;});

In your case, as you the studentID seems to serve as a "unique key", I'd use data structure std::map<int, StrudentGradeInfo> instead.

Overloading operator == is - as gsamars pointed out - somehow impractical, as it is meant for comparing two objects of the same type (and not an object with an int). See the following code illustrating this:

struct StudentGradeInfo {
    std::string studentName;
    int studentID;

    bool operator==(const StudentGradeInfo& c) const {
        return c.studentID == studentID;
    }
};

int main() {

    std::vector<StudentGradeInfo> gradebook {
        { "john", 123 },
        { "max", 345 }
    };

    StudentGradeInfo aNewOne { "sepp", 345 };
    auto it = find(gradebook.begin(),gradebook.end(),aNewOne);
    if (it == gradebook.end()) {
        cout << "345 does not exist" << endl;
    } else {
        cout << "345 already exists" << endl;
    }

}

Upvotes: 0

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

I guess you could do it like this if you absolutely have to make an overloaded operator==.

bool operator==(const StudentGradeInfo& sgi, int id) {
    return sgi.studentID == id; 
}

std::vector<StudentGradeInfo> gradebook;
int id_to_find=1234;

for(auto& sgi : gradebook) {
    if(sgi==id_to_find) {
        //...
    } 
}

Upvotes: 1

Related Questions