Vector of structures

Hey everyone,
I was working on my assignment and ran into a little bit of a roadblock. So i need to add students into a vector of structs that looks like this.

1
2
3
4
5
6
7
8
9
    struct students
    {
        string student_name;
        unsigned student_id;
    };


    vector<students> entries;
    students s;


So now my problem is that I need to verify that the student being added hasn't already been added to the vector using the same ID. This is what I got so far, but I can't figure out what I am doing wrong. Any insight would be helpful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool Course::addStudent (string name, int id)
{
    for(int i = 0; i < entries.size(); i++)
    {
        if(id == entries[i].student_id)
        {
            cout << "SORRY";
            return false;
        }
        else
        {
            s.student_name = name;
            s.student_id = id;
            entries.push_back(s);
            return true;
        }
    }
}


Thanks.
Try tracing your code. You don't really have a loop. You will always return from your function on the first iteration.

Basically, your code checks if the first element is equal to id, and if it is, it returns false, and if not, it just adds it to the vector and returns true. What you need to do, is move your adding-to-vector logic outside of the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool Course::addStudent (string name, int id)
{
    for(int i = 0; i < entries.size(); i++)
    {
        if(id == entries[i].student_id)
        {
            cout << "SORRY";
            return false;
        }
    }
    s.student_name = name;
    s.student_id = id;
    entries.push_back(s);
    return true;
}


Basically, because you return from the function if you find a match while looping over your vector, if you make it out of the loop and still haven't returned, you're guaranteed that there's no match.
Thanks for the response, can't believe I didn't catch that.
Topic archived. No new replies allowed.