Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a pointer to a current iterator value

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?

like image 775
slayton Avatar asked Dec 23 '11 17:12

slayton


2 Answers

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

like image 151
Nawaz Avatar answered Sep 24 '22 10:09

Nawaz


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?

like image 36
fredoverflow Avatar answered Sep 26 '22 10:09

fredoverflow