How to invalidate an iterator?

后端 未结 4 862
一个人的身影
一个人的身影 2021-01-14 23:44

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 i

相关标签:
4条回答
  • 2021-01-15 00:15

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

    template <typename Iter>
    void foo(Iter it){
      it = Iter(); // invalidate
    }
    
    0 讨论(0)
  • 2021-01-15 00:19

    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.

    0 讨论(0)
  • 2021-01-15 00:19

    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.

    0 讨论(0)
  • 2021-01-15 00:27

    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;

    0 讨论(0)
提交回复
热议问题