0
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?

mkmostafa
  • 3,071
  • 2
  • 18
  • 47

1 Answers1

1

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.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • That was my intuition. I dont want to store the iterators I would like to have the objects they point to without having to copy them (which will be expensive due to the size of these objects). – mkmostafa Feb 26 '16 at 11:53
  • Probably would have been better if you'd asked a question about what you are ACTUALLY trying to achieve, rather than presupposing that you need to store iterators in a container (which may be a red herring). But look up pointers and references as a starting point. – Peter Feb 26 '16 at 12:30