mkmostafa
mkmostafa

Reputation: 3171

Copying iterators of a container into another container of iterators before erasing it from the first

vector<obj> vec;
deque<iterator> q;
iterator it = vec.find(obj1);
q.push_back(it);
vec.erase(it);

I know that it will be copied into q but what I would like to know is will it point to something invalid?

Upvotes: 0

Views: 61

Answers (1)

Peter
Peter

Reputation: 36597

Iterators remain valid, until an operation is performed on the originating container that can invalidate them. The operations that can invalidate iterators depend on the type of container.

So, yes, it is possible to store iterators in a container. This is inadvisable, since there is nothing stopping the originating container from invalidating them - and no general/reliable way for code using the container of iterators to detect that, and avoid using an invalidated iterator.

Obtaining a valid iterator from a container is not a particulary expensive operation, so there are very few benefits in storing iterators anyway.

Upvotes: 1

Related Questions