this is my first time using the list STL and i’m not sure if what i’m trying to do is possible.
I have class_B which holds a list of class_A, I need a function in class_B that takes an ID, searches the list for an instance with the same ID, and gets a pointer form the list to the instance in that list:
bool class_B::get_pointer(int ID,class_A* pointer2A){
list<class_A>::iterator i;
for(i=class_A.begin();i!=class_A.end();i++){
if((*i).get_id()==ID) {
\\pointer2A=(i);<---------------this is what I'm trying to do
return true;
}
}
pointer2A=NULL;
return false;
}
how do I perform this, is it possible to convert from iterator to instance ?
EDIT:
I’m using this function in a multi-threaded program and I can’t return an iterator to the calling function since another thread might delete an element of the list.
Now that I have a pointer to my element(and lets say it’s locked so it can’t be deleted), and a different thread removed another element and performed a sort on the list, what will happen to the pointer I’m holding ? (I don’t know how the list rearranges the elements, is done by copying the elements using a copy c’tor, or by another mean?).
Useless answer was the most helpful in my case (BIG thanks), and yes I should use a reference to the pointer since I’m planing to change it.
iterators are designed to have similar semantics to pointers, so for example you can write
i->get_id()just as if you had a pointer to A.Similarly,
*iyields a referenceA&, and&*iconverts that back into a pointer – it looks a bit clunky (it would be an identity operation ifiwere really a pointer), but it’s idiomatic.Note that this won’t do what you presumably want anyway – the caller’s
class_A* pointer2Ais passed by value, so onlyget_pointer‘s copy of the pointer is modified, and the caller won’t see that value. Try this:Now
pointer2Ais passed by reference, so the caller’s copy gets modified inside your function.BTW, you can read the parameter declaration
class_A * & pointer2Aright-to-left, as “pointer2A is a reference to a pointer to class_A”.