Can I get a pointer to the current value of the iterator

In my class, I have two private members:

std::list<MyObject> objects; MyObject *selecteObj; 

When an event occurs, I would like to iterate through the list and run some kind of test that will only give true for one of the elements in the list. I would like to keep a pointer to this element for use elsewhere.

 std::list<MyObject>::iterator i; for (i = objects.begin(); i!=objects.end(); ++i){ if (i->test()) selectedObj = i; } 

In another place In another method

 if (selectedObj !=null) tmpObj->doSomething(); 

However, this does not work, because i not a pointer, its iterator, even if you can consider it as a pointer to MyObject .

Is it possible to retrieve the pointer that the iterator stores internally for use elsewhere?

Am I thinking about it wrong?

What is the correct way to accomplish what I'm trying to do?

+6
source share
2 answers

Is it possible to retrieve the pointer that the iterator stores internally for use elsewhere?

Of course, just search for an iterator with * , and then get a pointer to the object via & :

 selectedObj = &*i; 

On the other hand, did you remember to initialize selectedObj with NULL before the loop?

+13
source

Is it possible to retrieve the pointer that the iterator stores internally for use elsewhere?

Yes. As @FredOverflow said, do the following:

 selectedObj = &*i; 

However, if you can use the C ++ 11 functions, you can enjoy writing better syntax using a range-based for loop:

 MyObject *selectedObj = NULL; for (MyObject & obj : objects) { if (obj.test()) selectedObj = &obj; //store the address } 

Looks better? There is no need for an iterator and spelling syntax like &*i . It should also be noted that if the MyObject class is overloaded with operator & , then &*i will not work, since it will call the operator& function instead of getting the address of your object! If yes, then you write (MyObject*)&(char&)*i to get the address *i , or in C ++ 11 you can use std::addressof(*i) , which you can define yourself if you don’t can use c ++ 11:

 template< class T > T* addressof(T& arg) { return (T*)&(char&)arg; } 

Code taken from here: std :: addressof

+6
source

Source: https://habr.com/ru/post/904401/


All Articles