Checking if an iterator is valid

后端 未结 11 576
耶瑟儿~
耶瑟儿~ 2020-11-30 02:52

Is there any way to check if an iterator (whether it is from a vector, a list, a deque...) is (still) dereferencable, i.e. has not been invalidated?

I have been usi

11条回答
  •  执念已碎
    2020-11-30 03:27

    As jdehaan said, if the iterator wasn't invalidated and points into a container, you can check by comparing it to container.end().

    Note, however, that if the iterator is singular -- because it wasn't initialized or it became invalid after a mutating operation on the container (vector's iterators are invalidated when you increase the vector's capacity, for example) -- the only operation that you are allowed to perform on it is assignment. In other words, you can't check whether an iterator is singular or not.

    std::vector::iterator iter = vec.begin();
    vec.resize(vec.capacity() + 1);
    // iter is now singular, you may only perform assignment on it,
    // there is no way in general to determine whether it is singular or not
    

提交回复
热议问题