2

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?

3
  • First, I think it is not good idea to such behaviour. Second, you can store pointer to iterator. Commented Dec 6, 2010 at 5:41
  • 1
    if you really want someone may also explain how to get Undefined Behavior explicitely ;-) Commented Dec 6, 2010 at 7:08
  • Why would you want this? There's nothing you can do with the iterator afterwards that you couldn't do before. Commented Dec 6, 2010 at 10:01

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

try to limit the scope of your iterator by using additional blocks. Outside the block, the iterator isn't there anymore. That's better than invalid.
2

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;

Comments

1

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

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

2 Comments

This is very cool. I can get the iterator type directly, so the function is unnecessary. By the way, I think we need to pass it by reference, is this right?
in order to modify it, sure. This was just an example. The only reason I made it a function was that it was the easiest way to say "Assuming the iterator type is Iter and the iterator object is called it..." :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.