correct use of iterator to return an object from a list

c++

Solution

I have a list of meetings.

No, you don't. You have a list of pointers to meeting. From that one misunderstanding, all of your further errors flow.

if (it->getStartHour() == StartHour)

This code would be correct if you had a list of meetings. It is wrong if you have a list of pointers to meetings. Try:

if ((*it)->getStartHour() == StartHour)

Next:

return *it;

Try:

return **it;

In the alternative, perhaps you really do want a "list of meetings". In that case, you would declare your list thus:

std::list<meeting> meetings;

I don't know which you want -- a list of meetings or a list of pointers to meetings. That has to do with the design of the rest of your program. I almost never keep a container full of pointers.

You might want a list of pointers, for example, if you need multiple list entries to refer to the same meeting. ("I have a meeting at 10 with Abe, at 11 with Bob and Chuck, and then again a meeting at 10 with Abe"?)

You also might want a list of pointers if copying a `meeting` is impossible or prohibitively expensive. In that case, I suggest you use a smart pointer rather than a naked pointer.

To answer your other question, yes, returning a reference to an object is a fine thing to do. You do need to be aware of the lifetime of that object; never access the object through its reference after it is destroyed.

Problem

I have a list of meetings: ``` std::list<meeting*> meetings; ``` I want to iterate the list and return a reference to a specific meeting: ``` meeting& day::findMeeting( float StartHour ) { std::list<meeting*>::iterator it; for(it = meetings.begin(); it != meetings.end(); it++) { if (it->getStartHour() == StartHour) { return *it; } } throw no_such_meeting_error; } ``` i get the following errors : - `'getStartHour' : is not a member of 'std::_List_iterator<_Mylist>'` - `'return' : cannot convert from 'meeting *' to 'meeting &'` - `invalid return type 'meeting **' for overloaded 'operator ->'` I'm still learning c++ so would be happy to understand what i'm doing wrong. Also, - Is it good practice to return a reference to an object from a function ? Is there something better to do ? - is it likely that the reference will be invalidated on some because of changes to the items in the list ? Thanks

Original source