c++ - Can you find the iterator for a list element given a pointer to the element? -
the question pretty self-explanatory, if have std::list<t>
object, there standard method iterator element, given t*
value points element?
if t
user-defined type, seems dereferencing pointer , using find_if
job, seems inefficient me. if you're trying find element in container value, makes sense you'd need iterate through container until find something. if have pointer, intuitively feels there should method that's more direct. basic understanding makes me think there should 1-to-1 relationship between list item's iterator , pointer since lists doubly-linked in stl, don't have up.
i'm not familiar with c++ iterators, if explain why there or isn't way this, helpful.
edit: potatoswatter provided c++11 solution i'd still interested if c++03-compatible solutions available.
there's no standard algorithm find iterator in range satisfies condition. find
uses value of element, that's not same thing. find_if
lambda compares addresses work.
it's easy write generic version:
template< typename iter, typename t > iter iterator_from_ptr( iter first, iter last, t * ptr ) { while ( first != last ) { // c++03 compatibility, use &* first instead of addressof. if ( std::addressof( * first ) == ptr ) return first; ++ first; } return last; }
usage: iterator_from_ptr( my_list.begin(), my_list.end(), ptr )
.
as mention, inefficient, o(n) specific. going faster against rules of c++: have pointer object member of std::list
node, , list::iterator
pointer std::list
node. there's (usually) no way go pointer-to-member pointer-to-whole-object. (not mention iterator abstraction getting in way.)
Comments
Post a Comment