In my class I have two private members:
std::list<MyObject> objects;
MyObject *selecteObj;
When an event occurs I'd like to iterate through the list and run some sort of test that will only yield true on one of the items in the list. I'd like to save a pointer to that item for use elsewhere.
std::list<MyObject>::iterator i;
for (i = objects.begin(); i!=objects.end(); ++i){
if (i->test())
selectedObj = i;
}
Elsewhere In another method
if (selectedObj !=null)
tmpObj->doSomething();
However this doesn't work because i
isn't a pointer, its an iterator even though you can treat it like a pointer to an MyObject
.
Is it possible to retrive the pointer that the iterator is storing internally for use elsewhere?
Am I thinking about this incorrectly?
What is the proper way of accomplishing what I'm trying to do?
Is it possible to retrive the pointer that the iterator is storing internally for use elsewhere?
Yes. As @FredOverflow said, do this:
selectedObj = &*i;
However, if you can use features of C++11, then you can enjoy writing better syntax using range-based for
loop as:
MyObject *selectedObj = NULL;
for (MyObject & obj : objects)
{
if (obj.test())
selectedObj = &obj; //store the address
}
Looks better? No need of iterator and writing syntax like &*i
. It should be also noted that if the class MyObject
has overloaded operator &
, then &*i
wouldn't work, as it would invoke the operator&
function, instead of getting you the address of the object! If so, then you've write (MyObject*)&(char&)*i
to get the address of *i
, or in C++11 you can use std::addressof(*i)
which you can define yourself if you cannot use C++11:
template< class T >
T* addressof(T& arg) {
return (T*)&(char&)arg;
}
Code taken from here : std::addressof
Is it possible to retrive the pointer that the iterator is storing internally for use elsewhere?
Sure, just dereference the iterator with *
and then get a pointer to the object via &
:
selectedObj = &*i;
On a side note, did you remember to initialize selectedObj
with NULL
before the loop?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With