Thomson
Thomson

Reputation: 21615

How to invalidate an iterator?

Since I know an iterator in the program could be invalidated by some previous operation, I want to invalidate it explicitly. Such as assign NULL to a pointer to invalidate it, I just want to do the same on iterator. container.end() could not be the precise idea here. I tried to assign NULL to my iterator, but it failed. How can I get the same behavior of NULL pointer on iterator?

Upvotes: 2

Views: 975

Answers (4)

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247919

Shouldn't this always work? (iterators are always assignable and default-constructible)

template <typename Iter>
void foo(Iter it){
  it = Iter(); // invalidate
}

Upvotes: 1

MSalters
MSalters

Reputation: 179779

You can't, in general. There are some iterators that cannot be invalidated at all. For instance, a random number generator can be modelled as an output iterator, with operator* returning the current number and operator++ generating a new one.

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61498

could be invalidated by some previous operation, I want to invalidate it explicitly

... If you know it may not be valid, then all you have to do it stop using it. Invalidating the iterator explicitly accomplishes nothing, because using it is a programming error either way.

Upvotes: 4

Juarrow
Juarrow

Reputation: 2384

Why don´t You want to use container.end() ?... it works for most containers...

For std::string You may want to check , wether the position is yourstring.npos;

Upvotes: 2

Related Questions