Luis
Luis

Reputation: 1348

Get iterator from pointer

Following question Segmentation fault executing method I stopped in another problem.

Given:

Cluster * base;
Cluster * absorbed;

list<Cluster>::iterator li = clusters.begin();

// li is then pointed to some element.

absorbed = &(*li);   // Get a pointer to the chosen element.

base->joinCluster(absorbed);   // Perform an action with absorbed.

// li contines the cycle and now point to clusters.end()

// Now, absorbed should be deleted from list. li doesn't point to absorbed anymore.
li = & (* absorbed);
clusters.erase(li);

Tried to do the reverse of above, but g++ returns an error: error: no match for 'operator=' in 'li = absorbed' How can I do this?

I'm trying to avoid to cycle through all the elements in the list to find again the absorbed one.

Edit:

Sorry, but i understand I missed to say that after absorbed = &(* li); li continues to cycle until clusters.end(). So, at the time the cycle ends, li doesn't point to absorbed anymore. I think I have two option: Either I cycle again through all elements in clusters to find the absorbed element; Or I take advantage of the absorbed pointer to erase the element from clusters. But, how can I achieve this second option?

Upvotes: 0

Views: 759

Answers (4)

Marius
Marius

Reputation: 837

instead of

// Now, absorbed should be deleted from list
li = & (* absorbed);
clusters.erase(li);

use:

clusters.pop_front();

if you always process the first element.

There is no way to obtain an iterator from a value. Not the reason but the same value can be in multiple containers or more then once in one.

Upvotes: 0

Stormenet
Stormenet

Reputation: 26468

Just erase it!
No need for trying to put a value back in if you are going to delete it anyway.

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363507

You cannot get an std::list<T>::iterator from a T*. You'll have to use the original li to perform iterator operations.

Upvotes: 3

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36433

Just skip the li = &(*absorbed) line and it should work fine.

Upvotes: 4

Related Questions